使用ID删除DB行

时间:2014-12-01 11:40:40

标签: php html mysql

我的每一行旁边都有一个应该删除它的“拒绝”按钮。 问题是,在我点击之后,没有任何反应,我不知道为什么。

是否可能与ID设置为AUTO_INCREMENT的事实有关?

所以我用MySQL做表:

enter image description here

然后我创建了一个网页,将代码翻译成:

enter image description here

最后,这是代码:

<?php

    include('connect-mysql.php');

    $sqlget = "SELECT * FROM kunden";
    $sqldata = mysqli_query($dbcon, $sqlget) or die('Error!');

    echo "<table>";
    echo "<tr><th>KundenID</th>.....<th>Telefon</th></tr>";
    while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)) {
        echo "<tr><td>";
        echo $row['kundenid'];
        echo "</td><td>";
        .......................
        .......................
        echo $row['telefon'];
        echo "</td><td>";
        echo '<button onclick="window.location=delete.php?id='.$row['kundenid'].'">Delete</button>';
        "</td></tr>";
    }

echo "</table>";

?>  

我的delete.php:

<?php
if(isset($_GET['id'])) {
      // delete the row based on the `id` parameter
      $id = $_GET['id'];
      mysqli_query($dbCon, "DELETE FROM kunden WHERE kundenid = ".$id);

}
?>

1 个答案:

答案 0 :(得分:0)

首先,我建议只是正常提交​​表单而不是创建重定向:

echo '<form method="POST" action="delete.php">';

    echo "<table>";
        echo "<tr><th>KundenID</th>.....<th>Telefon</th></tr>";
        while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)) {
            echo "<tr><td>";
            echo $row['kundenid'];
            echo "</td><td>";
            .......................
            .......................
            echo $row['telefon'];
            echo "</td><td>";
            echo '<button type="submit" name="delete" value="'.$row['kundenid'].'">Delete</button>';
            "</td></tr>";
        }

    echo "</table>";

echo '</form>';

然后在delete.php上,不要忘记连接。无论如何,它不在问题范围内:

因为它的mysqli,为什么不使用准备好的声明:

<?php
if(isset($_POST['delete'])) {

    $dbCon = new mysqli('localhost', 'username', 'password', 'database_name');
    $id = $_POST['delete'];
    $sql = 'DELETE FROM kunden WHERE kundenid = ?';
    $delete = $dbCon->prepare($sql);
    $delete->bind_param('i', $id);
    $delete->execute();

    if($delete->affected_rows > 0) {
        header('Location: back_to_telefons_page.php');
        exit;
    }

}
?>