PHP删除按钮始终开始删除最后一行

时间:2015-11-02 07:38:40

标签: php mysql

booklist.php on webbrowser在此处输入图片说明

Database Table Contents

Database Table Structure

好吧,所以这对你们来说可能很简单,因为你们有经验,但我无法弄清楚为什么每次我都会这么做?#34;删除"我的表格的第一行上的按钮,它删除了最后一行而不是我点击的行#34;删除。"仅发生在第一行。第二行将完全删除数据库。

我的代码有什么问题或我的表结构有问题吗?我提供了两个独立的php文件的代码,即booklist.php和edit.php我很感激你的帮助,因为我是PHP的新手。还不熟悉所有规则,什么不是。感谢。

//booklist.php below
echo "<form method='POST' action='edit.php'>";
    while($row = mysql_fetch_array($result))
    {
    $bookID_Var = $row['No'];
    $titleVar = $row['Title'];
    $authorVar = $row['Author'];  //authorVar is a variable container for the value of Author row in librarydatabase
    $ISBN = $row['ISBN'];

    echo "<tr>";
        echo "<td>" .$bookID_Var. "</td>";
        echo "<td>" . $titleVar. "</td>";   // there's no need to quote variables. In this line, we used variables $authorVar and $titleVar
        echo "<td>" . $authorVar. "</td>";
        echo "<td>" . $ISBN . "</td>";
        echo "<td> <input type='submit' value='Edit'> </td>"; // Edit button
        echo "<td> <input type='submit'  name='delete' value='Delete'> </td>"; // Delete button

        echo "</tr>"; 
    echo "<input type='hidden' name='bookID' value='  " .$bookID_Var. "  '>";

    } // end of while loop

    echo "</form>";



//edit.php below

<?php
if (isset($_POST['delete'])) {
    echo "entered delete if block <br />";
    echo "Value: " . $_REQUEST['bookID'];

    $bookID = $_REQUEST['bookID'];
    $sql = " DELETE FROM booklist WHERE No='$bookID'  ";
    $result = mysql_query($sql);

    if ($result) {
        echo "Successfully deleted" . "Book ID: " . $bookID;
    }
} // end of main if
?>

5 个答案:

答案 0 :(得分:0)

首先。遵循惯例。将您的primary keys命名为id。第二 - 尝试回应你的query。您确定,如果您的$_REQUEST['bookID'] == 14?: - )

答案 1 :(得分:0)

替换

 $sql = " DELETE FROM booklist WHERE No='$bookID'  ";

echo  $sql = " DELETE FROM booklist WHERE No=".$bookID;exit;

并测试传递了哪个id我确定存在传递id的问题。

答案 2 :(得分:0)

您应该使用链接操作而不是根据行提交要删除的操作:

E.g:

变化:

<input type='submit'  name='delete' value='Delete'>

<a href="edit.php?bookID=<?php echo $row['No'] ?>">Delete</a>

答案 3 :(得分:0)

如果您对整个数据集使用一个表单,则隐藏字段在每一行中都将具有相同的名称。似乎最后一个覆盖了所有以前的。

有更好的方法来传递每行的id,一个简单的方法是将删除逻辑分离到delete.php,然后你可以将删除按钮作为链接,而不是表单,并将每行链接到delete.php?bookid=<id>

答案 4 :(得分:0)

尝试这种方法: -

使用hyperlink而不是input

echo "<a href='edit.php?act=delete&id=<?php echo $bookID; ?> '>Delete</a>"; 

或php代码: -

<?php
if(isset($_GET['act']) && $_GET['act']=='delete'){
$bookID=$_GET['act'];
 $sql = " DELETE FROM booklist WHERE No='$bookID'  ";
}