我正在尝试根据它的ID从数据库中删除一行。用户应该能够单击删除按钮,并且该行中的所有内容都应该被删除 - 根据我在下面的代码,它有点工作,但它会从表中删除所有行,而不是仅删除基于ID。
我感谢您看到的任何代码可能不是最佳实践,但这只是在个人项目的基本测试阶段,以便我更好地学习PHP。
我做错了什么?
try {
$results = $db->query("SELECT * FROM property_details ORDER BY id ASC");
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
$property = $results->fetchAll(PDO::FETCH_ASSOC);
echo '<form method="post">';
echo '<table><th> Property Name </th><th> Description </th><th> Host Name </th><th> Location </th><th> Price </th>';
foreach ($property as $property_details) {
$id = $property_details['id'];
echo '<tr>';
echo '<td>';
echo $property_details['property_name'] . '<br />';
echo '</td>';
echo '<td>';
echo $property_details['property_description'] . '<br />';
echo '</td>';
echo '<td>';
echo $property_details['host_name'] . '<br />';
echo '</td>';
echo '<td>';
echo $property_details['location'] . '<br />';
echo '</td>';
echo '<td>';
echo "£" . $property_details['price'] . " per night";
echo '</td>';
echo '<td>';
echo '<input type="submit" name="deleteItem" value="DELETE ID '.$id.'" />';
echo '</td></tr>';
if(isset($_POST['deleteItem'])) {
try {
$results = $db->prepare("DELETE FROM
property_details
WHERE
id = :theid
");
$results->bindParam(':theid', $id);
$results->execute();
}
catch (Exception $e) {
echo "Could not insert data in to the database";
}
}
}
echo '</table>';
echo '</form>';
答案 0 :(得分:0)
整理处理的粗略方式。
这将获取deleteItem的calue,根据空间将其展开,并使用第3项作为要删除的项目的ID: -
<?php
if(isset($_POST['deleteItem']))
{
list($filler, $filler2, $id_to_delete) = explode(' ', $_POST['deleteItem']);
if (is_numeric($id_to_delete))
{
try
{
$results = $db->prepare("DELETE FROM
property_details
WHERE
id = :theid
");
$results->bindParam(':theid', (int)$id_to_delete);
$results->execute();
}
catch (Exception $e)
{
echo "Could not delete data from the database";
}
}
}
try
{
$results = $db->query("SELECT id, property_name, property_description, host_name, location, price FROM property_details ORDER BY id ASC");
} catch (Exception $e)
{
echo "Data could not be retrieved from the database.";
exit;
}
$property = $results->fetchAll(PDO::FETCH_ASSOC);
echo '<form method="post">';
echo '<table><th> Property Name </th><th> Description </th><th> Host Name </th><th> Location </th><th> Price </th>';
foreach ($property as $property_details)
{
$id = $property_details['id'];
echo '<tr>';
echo '<td>';
echo $property_details['property_name'] . '<br />';
echo '</td>';
echo '<td>';
echo $property_details['property_description'] . '<br />';
echo '</td>';
echo '<td>';
echo $property_details['host_name'] . '<br />';
echo '</td>';
echo '<td>';
echo $property_details['location'] . '<br />';
echo '</td>';
echo '<td>';
echo "£" . $property_details['price'] . " per night";
echo '</td>';
echo '<td>';
echo '<input type="submit" name="deleteItem" value="DELETE ID '.$id.'" />';
echo '</td></tr>';
}
echo '</table>';
echo '</form>';
?>
可能应该检查第三部分是否是要删除的有效项目(即有效身份证)