【发布时间】:2017-10-10 00:33:43
【问题描述】:
我有以下代码,但未能删除记录,我想我可能遗漏了一些东西。
<?php
//Open Database
class MyDB extends SQLite3
{
function __construct() {
$this->open('Name.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
}
//Select the Name Table
$sql =<<<EOF
SELECT * FROM Name;
EOF;
$ret = $db->query($sql);
// Display The Data In a Table
echo "<table border='1' cellpadding='10'>";
echo "<tr><th>First name</th> <th>Last Name</th> <th>Gender</th> <th></th>
<th></th></tr>";
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<tr>";
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['LastName'] . '</td>';
echo '<td>' . $row['Gender'] . '</td>';
echo '<td><a href="name.php?id=' . $row['FirstName'] . '">Delete</a>
</td>';
echo "</tr>";
}
// check for id to be set and if it is delete the matching row from database
if (isset($_GET['id']))
{
// puts the id value in the variable
$id = $_GET['id'];
// delete the entry
$db->exec("Delete FROM Name WHERE VALUES TeamName=$id;");
header("Location: name.php");
} else {
header("Location: name.php");}
$db->close();
?>
我是否缺少某些东西,因为它仍然不会从 db 文件中删除整行。显示完美的表只是未能删除匹配的 id 记录。
我尝试过的其他删除查询是
$db->exec("Delete FROM Name (FirstName, LastName, Gender) WHERE VALUES
FirstName=$id;");
【问题讨论】:
-
警告:这有一些严重的SQL injection bugs,因为在查询中使用了用户数据。尽可能使用准备好的语句。在
mysqli和PDO 中执行这些操作非常简单,其中任何用户提供的数据都使用?或:name指示符指定,稍后使用bind_param或execute填充,具体取决于您是哪个使用。 切勿将$_POST、$_GET或任何用户数据直接放在您的查询中。 -
不能删除列值,只能删除整行。请参阅how
DELETEworks 上的手册。随意拼凑语法并不是学习 MySQL 的有效方法。