PHP从数据库中删除不起作用

时间:2013-03-24 23:25:07

标签: php mysql database

我试图让用户检查要删除的项目。当用户勾选一个或多个项目并单击“删除”按钮时,这些数据将从数据库中删除。我还添加了一个搜索框来搜索DVD。搜索框有效,但删除却没有。这就是它在浏览器中的样子。

PHP deleting

我的PHP看起来像这样(我拿出搜索代码):

<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<p><input type="submit" name="deleting" value="Delete"></p>
</form>
<?php   
    $link = mysqli_connect( $host, $user, $password, $dbname);
    if (!$link) {
        die('Could not connect: ' . mysqli_connect_error());
    }
    echo 'Connected successfully<br/>';

//searching code goes here 

if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
$deleteThese = implode(",", $_POST['deleteThese']); 
$queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)"; 
$resultTwo = mysqli_query($link, $queryTwo);
}

echo "<table border=\"1\"><tr><th>DvdTitle</th><th>RunningTime</th><th>Delete</th></tr>";
if (mysqli_num_rows($result) == 0)
   echo "<tr><td colspan='2'>No records found.</td></tr>";

   else {
    while ($row = mysqli_fetch_assoc($result)) {
    echo "<tr><td>" . $row['DvdTitle'] . "</td>";
    echo "<td>" . $row['RunningTime'] . "</td>";
    echo "<td>" . "<form>" . "<input type='checkbox' name='deleteThese[]' value='" . $row['DvdID'] . "' >" . "</form>" . "</td></tr>\n"; 
           }
        }
    echo "</table>";
    mysqli_free_result($result);
    mysqli_close($link);
?>

每个DvdTitle都有一个唯一的Dvd ID,因此每行的值是dvd的ID $row['DvdID']

2 个答案:

答案 0 :(得分:1)

添加括号将允许选择这些ID进行删除。

 IN($deleteThese)

修改

请勿在提交按钮后关闭表单。把它放在代码的末尾。这将允许表单包含复选框值。

<form action="" method="post">
<p><input type="text" name="search"> <input type="submit" value="Search"></p>
<!-- YOUR PHP CODE -->
<p><input type="submit" name="deleting" value="Delete"></p>
</form>

第二次编辑[要求改进代码]

将isset移动到表单顶部。

<?php
if (isset ($_POST['deleting']) && isset ($_POST['deleteThese']) )
{
  $deleteThese = implode(",", $_POST['deleteThese']); 
  $queryTwo = "DELETE FROM `$dbname`.`dvds` WHERE `dvds`.`DvdID` IN ($deleteThese)"; 
  $resultTwo = mysqli_query($link, $queryTwo);
}
?>
<form>....

答案 1 :(得分:0)

$deletethese可能需要引用它。