如何从表中删除记录?

时间:2010-07-31 08:11:24

标签: php

我正在使用表单来获取用户名和密码的输入以将值存储到数据库中,一旦提交表单我已经定义了一个表来显示来自users表的所有值,它有3个字段(id ,name,pass)我想用它的id删除每条记录。

我使用以下代码从users表中获取数据:

while($row = mysql_fetch_assoc($result_select)) {
           echo "<tr>";
           echo "<td>" . $row['id'] . "</td>";
           echo "<td>" . $row['name'] . "</td>";
           echo "<td>" . $row['pass'] . "</td>";
           echo "</tr>"; }

我想添加删除超链接以按ID删除特定记录。

我尝试使用以下代码,但我无法实现它。

if(mysql_num_rows($result_select) > 0) {

        if(isset($_POST['id'])) {
             $query_delete = "DELETE FROM users WHERE id =" .$_POST['id']; 
             $result_delete = mysql_query($query_delete);

        }
       echo "<table cellpadding=10 border=1>";
        while($row = mysql_fetch_assoc($result_select)) {

           echo "<tr>";
           echo "<td>" . $row['id'] . "</td>";
           echo "<td>" . $row['name'] . "</td>";
           echo "<td>" . $row['pass'] . "</td>";
           echo "<td><a href=".$_SERVER['PHP_SELF']."?id=".$row[id].">Delete</a></td>"; 
           echo "</tr>";
        }
  echo "</table>";
    }

我是编程的新手,如果有人用简单的话语解释我,我将不胜感激..谢谢:)

2 个答案:

答案 0 :(得分:1)

首先将您的删除代码放在您的页面中,如下所示:

   if(isset($_POST['submit'])) {

         for($i = 0; $i < count($_POST['del']); $i++)
         {
           // check which records to delete
           if (isset($_POST['del'][$i]))
           {
             $query_delete = "DELETE FROM users WHERE id = " . (int) $_POST['del'][$i];
             $result_delete = mysql_query($query_delete) or die(mysql_error());
           }
         }

         echo 'Record Deleted !!' . '<br /><br />';
    }

稍后输入您的选择代码并按如下方式修改:

echo '<form action="" method="POST">';
while($row = mysql_fetch_assoc($result_select)) {
       echo "<tr>";
       echo "<td>" . $row['id'] . "</td>";
       echo "<td>" . $row['name'] . "</td>";
       echo "<td>" . $row['pass'] . "</td>";
       echo "<td><input type=\"checkbox\" name=\"del[]\"></td>";
       echo "</tr>";
}
echo '<input type="submit" name="submit">';
echo '</form>';

答案 1 :(得分:0)

您需要将$_POST更改为$_GET,这样才有效。

if(isset($_GET['id'])) {
    $query_delete = "DELETE FROM users WHERE id =" .$_GET['id']; 
    $result_delete = mysql_query($query_delete);

并且还将属性值放在双引号内,如此

echo '<td><a href="'.$_SERVER['PHP_SELF'].'?id='.$row[id].'">Delete</a></td>';