使用HTML表单和PHP从MYSQL数据库中删除记录

时间:2016-03-15 13:55:41

标签: php forms mysqli

我刚开始使用PHP和MySQL。我创建了一个带有id,firstname,lastname和age的示例数据库。然后我设法用addStudent.php创建一个HTML表单,这样就可以用这种方式添加数据。但是,我想尝试使用表单删除数据。理想情况下,我只希望删除发生在所有字段匹配但不知道如何用WHERE表达它。

我在这方面遇到了麻烦,所以会感激一些帮助。我的index.php是:

<?php 
 $db_host = "localhost";
 $db_user = "root";
 $db_pass = "root";
 $db_name = "course";
 ?>

<!DOCTYPE html>
<html>
<head>
    <title>Students</title>
</head>
<body>
<h1>Student Database</h1>
<?php
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

 if (mysqli_connect_errno()) {
        printf("connection failed: %s\n", mysqli_connect_error());
        exit();
    } else {
        echo "we have a connection";
    }

$query = "SELECT * FROM students";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "<p>".$row['firstname']." ".$row['lastname']."</p>";
    }
} else {
    echo 'NO RESULTS';
}
 ?>
<h2>Delete Student</h2>
 <form action="deleteStudent.php" method="POST">
    <p>
        <label for="firstname">First name:</label>
        <input id="firstname" name="firstname" type="text">
    </p>
    <p>
        <label for="lastname">Last name:</label>
        <input id="lastname" name="lastname" type="text">
    </p>
    <p>
        <label for="age">Age:</label>
        <input id="age" name="age" type="text">
    </p>
    <input type="submit" value="submit">
 </form>
</body>
</html>enter code here

我的deleteStudent.php是:

<?php 
$db_host = "localhost";
$db_user = "root";
$db_pass = "root";
$db_name = "course";

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
} else {
    echo "We have a connection!";
}


?>
 <!DOCTYPE html>
 <html>
 <head>
    <title>Delete Student</title>
 </head>
 <body>
    <h2>Delete a student</h2>
    <?php 

        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $age = $_POST['age'];

        $query = "DELETE FROM students WHERE firstname=$firstname (
        NULL,
        '".$_POST['firstname']."',
        '".$_POST['lastname']."',
        '".$_POST['age']."')";

        $mysqli->query($query) or die($mysqli->error.__LINE__);
     ?>
    <p>Student deleted!</p>
 </body>
 </html>

1 个答案:

答案 0 :(得分:1)

此查询将删除表中相同名字的所有寄存器。

$query = "DELETE FROM students WHERE firstname='$firstname'";

注意$firstname周围缺少的撇号。他们需要让MYSQL理解这是一个字符串。否则它会'认为'它是一个列名。

查询的其余部分失败,因为您添加了一些您不需要的括号,因为它将根据您的WHERE条件删除整个行。如果您希望添加额外的过滤器,则需要添加ANDOR子句以获取更具体的行。

像这样:WHERE firstname='$firstname' AND email='$email'

如果您只想删除特定的人,则必须开始使用您必须已经听说过的称为主键的唯一ID。