2017-05-25 85 views
0

我已經顯示的HTML表格,表格中管理員查看用戶信息。我創建了一個鏈接/圖標來刪除特定用戶(行),但我收到500內部服務器錯誤。刪除SQL行與jQuery/Ajax和PHP

他們是這裏的另一個類似的問題這讓我很遠,但我仍收到錯誤

我的表:

$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內部服務器錯誤,如何解決?謝謝。

+0

你的代碼是脆弱的[** SQL注入**](https://en.wikipedia.org/wiki/SQL_injection)攻擊。你應該使用[** mysqli **](https://secure.php.net/manual/en/mysqli.prepare.php)或[** PDO **](https://secure.php.net/ manual/en/pdo.prepared-statements.php)準備帶有綁定參數的語句,如[**這篇文章**]所述(https://stackoverflow.com/questions/60174/how-can-i-prevent-sql步噴射功能於PHP)。 –

+0

不要使用'mysql_ *'功能。自v5.5(2013年6月)開始,它們已被棄用,並從v7.0(2015年12月)開始刪除。請使用[** mysqli _ ***](https://secure.php.net/manual/en/book.mysqli.php)或[** PDO **](https://secure.php.net /manual/en/book.pdo.php)與[**準備語句**](https://secure.php.net/manual/en/pdo.prepare.php)和[**綁定參數** ](https://secure.php.net/manual/en/pdostatement.bindparam.php)。 –

+0

知道了謝謝! – DLzer

回答

0

多個問題:

更新你的SELECT查詢從表

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

$row得到id是一個關聯數組不是object`

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

沒有必要使用單引號一個整數

$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)); 
+0

這工作完美。我將從現在開始使用PDO準備的語句。謝謝! – DLzer