使用jQuery / Ajax和PHP

时间:2017-05-25 16:36:38

标签: php jquery ajax

我已经显示了一个包含管理员查看用户信息的html表。我创建了一个链接/图标来删除特定用户(行),但我收到500内部服务器错误。

他们是另一个类似的问题,这让我相当远但我仍然收到错误

我的表:

$query = "SELECT zone, firstname, lastname, email, business, reg_date, phone FROM UserList";
      // Display users is a table format
      $result = $conn->query($query);
      if ($result->num_rows > 0) {
          // output data of each row
          while($row = $result->fetch_assoc()) {
              echo "<tr><td> " . $row["zone"]. "</td><td> " . $row["firstname"]. "</td><td> " . $row["lastname"] . "</td><td> " . $row["email"]. "</td><td> " . $row["business"]. "</td><td> " . $row["reg_date"]. " <a class='deleteRow' id='.$row->id.' href=''><i class='fa fa-times' aria-hidden='true'></a></td></i></tr><br> ";
          }
      } else {
          echo "<div class='no_results'>No Users Added</div>";
      }

我的jQuery / Ajax:

$(function(){
    $(document).on('click','.deleteRow',function(){
        var del_id= $(this).attr('id');
        var $ele = $(this).parent().parent();
        $.ajax({
            type:'POST',
            url:'removeUser.php',
            data:{'del_id':del_id},
            success: function(data){
                 if(data=="YES"){
                    $ele.fadeOut().remove();
                 }else{
                        alert("can't delete the row")
                 }
             }

            });
        });
});

我的removeUser文件:

<?php
include('config.php');
$user_id = $_POST['del_id'];
//echo $user_id
$qry = "DELETE FROM UserList WHERE id = '$user_id'";
$result = mysql_query($qry);
if(isset($result)) {
  echo "YES";
} else {
  echo "NO";
}
?>

为什么我收到500内部服务器错误,我该如何解决?感谢。

1 个答案:

答案 0 :(得分:0)

多个问题:

1 更新您的选择查询以从表

获取id
$query = "SELECT id, zone, firstname, lastname, email, business, reg_date, phone FROM UserList";

2 $row是一个关联数组,而不是对象`

<a class='deleteRow' id='.$row['id'].'>

3 无需使用带整数值的单引号

$qry = "DELETE FROM UserList WHERE id = $user_id";

注意:您应该使用 Mysql PDO 预备语句来避免SQL Injection如下所示:

$con =  new PDO( "mysql:host=".$dbHost.";"."dbname=".$dbName, $dbUsername, 
$dbUserPassword); 
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$qry = "DELETE FROM UserList WHERE id = ?";
$q = $con->prepare($qry);

$response = $q->execute(array($user_id));