jQuery php从mysql中动态删除表中的行

时间:2016-02-22 20:00:22

标签: php jquery mysql

我有一个页面,其中我有'lesson_id'定义的表行ID,我有一个jquery删除函数,删除该行而不必更改页面。 它几乎全部工作,但是当它将信息发布到delete_row.php时,它不会删除记录。 但是delete_row.php正在运行,因为我手动完成了delete_row.php?id = 4并且它成功删除了该记录。 任何指针和解释都会很棒,因为我还在学习。

lessons.php

<table id="lessons" class="table-hover">
    <thead>
        <tr>
            <th>Lesson ID</th>
            <th>Lesson Name</th>
            <th></th>
        </tr>
    </thead>
<tbody>
<?php 
while($row=mysqli_fetch_array($result)){
    echo '<tr id="'. $row['lesson_id'].'">';    
        echo '<td>'. $row['lesson_id'] .'</td>';
        echo '<td>'. $row['name'] .'</td>';
        echo '<td><a class="delete">Delete</a></td>';   
    echo '</tr>';
}
?>
</tbody>
<div id="error"></div>
<script>
$(document).ready(function()
{
    $('table#lessons td a.delete').click(function()
    {
        if (confirm("Are you sure you want to delete this row?"))
        {
            var id = $(this).parent().parent().attr('id');
            var data = 'id=' + id ;
            var parent = $(this).parent().parent();
            //$('#error').html(data);
            $.ajax(
            {
                   type: "POST",
                   url: "delete_row.php",
                   data: data,
                   cache: false,

                   success: function()
                   {
                    parent.fadeOut('slow', function() {$(this).remove();});
                   }
             });
        }
    });
});
</script>

delete_row.php

<?php
include ('../../../config.php');
$con = mysqli_connect ($dbhost,$dbuser,$dbpass,$dbname);
if (!$con){
    die('could not connect: '. mysqli_error($con));
}
$error = "";
$success = "";

if($_GET['id'])
{
$id = $_GET['id'];

mysqli_query($con,"DELETE FROM module_lessons WHERE lesson_id='$id'");
}
?>

显而易见......它没有对它进行SQL注入保护。

1 个答案:

答案 0 :(得分:2)

$_GET['id'];更改为$_POST['id'];

在这里,您正在执行POST请求:

type: "POST",
url: "delete_row.php",

...但是在您的PHP脚本中,您正在检查GET

此外,正如marc b所述,您目前很容易受到SQL注入攻击。请查看使用mysqli_real_escape_stringbind_param