2016-06-09 63 views
1

我对我的index.php页面有一个评论部分。 (就像我在这里显示的那样)我有一个删除链接,将您发送到删除页面。我希望能够在单击时删除该特定ID。 的index.php从Mysqli中删除选定的ID

<div class='commentnest'> 
       <p id='id'> ".$row['id']."</p> 
       <p id='user'> ".$row['user'].":</p> 
       <p id='comment'>".$row['usercomment']." </p> 
       <p id='time'>".$row['timestamp']."</p> 
       <a href='delete.php?=".$row['id']."'>Delete</a> 
     </div> 

delete.php页

if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 
$sql = "DELETE FROM commenttable WHERE id=id"; 
if (mysqli_query($conn, $sql)) { 
    echo "Record deleted successfully"; 
} else { 
    echo "Error deleting record: " . mysqli_error($conn); 
} 
mysqli_close($conn); 
?> 
每次我发送一个特定的评论有时间

,它会删除所有的意见。我知道这是因为我没有说明要选择哪个ID,但我很难搞清楚。

感谢您的帮助!

+2

阅读 - http://php.net/manual/en/tutorial.forms.php – splash58

+2

'id = id'为true。 http://sqlfiddle.com/#!9/add33/3首先命名您的'GET'参数。然后使用参数化查询删除该值。 – chris85

+0

您需要一个GET数组用于此 –

回答

1

所有记录都被删除,因为id=id将始终为true,除非id为NULL。您需要正确地从HTML传递:

<a href='delete.php?id=".$row['id']."'>Delete</a> 

,然后适当地在查询中使用它:

$sql = "DELETE FROM commenttable WHERE 
    id='".mysqli_escape_string($conn,$_REQUEST["id"])."'" ; 

如果ID始终是一个整数,你可以写简单:

$sql = "DELETE FROM commenttable WHERE 
    id=".(int)$_REQUEST["id"]); 
+0

[Little Bobby](http://bobby-tables.com/)说*** [您的脚本存在SQL注入攻击风险。](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql -injection-in-php)***了解[MySQLi]的[prepared](http://en.wikipedia.org/wiki/Prepared_statement)语句http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)。即使[转义字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)是不安全的! –

+0

mysqli_escape_string()或将用户输入转换为int将删除SQL注入的可能性。虽然预处理语句也可以防止SQL注入,但这不是唯一的方法。 –

+1

转义字符串,而一个好主意,可以被击败。无论如何 - 道具给你和你的奔跑家庭!你们都比我快! ¯\\ _(ツ)_ /¯ –