首页 > 解决方案 > 无法删除php中的记录

问题描述

我创建了一个显示在网站上的数据库,也可以插入值。我试图删除记录。

这段代码是create.php,它创建了一个带有name ageemailnum2的表单cal(cal 只是添加agenum2查看计算的工作原理)。我们插入值并显示有一个表的数据库信息,该表info. db_connect.php将我们连接到数据库并使用该数据库。db()是一个函数db_connect.php.


    <?php



include "db_connect.php";




if(isset($_POST['submit'])) 
{    
    $name = $_POST['name'];
     $age = $_POST['age'];
     $email = $_POST['email'];
     $num2 = $_POST['num2'];
     $cal = $age + $num2;

     db();
     $insertQuery = "INSERT INTO info(name,age,email,num2,cal) VALUES ('$name','$age','$email','$num2','$cal')";
     $insertInfo = mysqli_query($link,$insertQuery);
    if($insertInfo)
    {
        echo "works";
    }else
    {
        echo mysqli_error($link);
    }


 }



    $showTable = "SELECT name,age,email,num2,cal FROM info";
    $result = mysqli_query($link, $showTable);

    if(mysqli_num_rows($result)>0)
    {
        echo "<table><tr><th>name</th><th>age</th><th>email</th><th>num2</th><th>cal</th></tr>";
        while($row = mysqli_fetch_assoc($result))
        {
            echo "<tr>
            <td>" . $row["name"]. "</td><td>" . $row["age"]. "</td><td>" . $row["email"]. "</td><td>" . $row["num2"]. "</td><td>" . $row["cal"]. "</td>";
            echo "<td><a href='delete.php? delete =$row[age]'>delete</a></td>";
            echo "</tr>";

        } 
        echo "</table>";
    }
    else 
    {
        echo "0 results";
    }

 mysqli_close($link);

?>

每行都有一个删除链接,该链接使用删除页面删除数据,然后再返回 create.php。这是删除.php:

<?php

include "db_connect.php"; 

$age = $_GET['age'];

$delete = mysqli_query($link,"delete from info where age = '$age'"); // delete query

if($delete)
{
    header("location:create.php"); 
    exit;   
}
else
{
    echo "Error";
}
?>

我正在尝试使用年龄来删除数据。如果我硬编码年龄。例如,如果我从 info 中写入 delete,where age = 21;它就可以工作。所有数据age 21都被成功删除。但是,如果使用此代码,则不会发生任何事情。

标签: phphtmlmysqldatabase

解决方案


URL 包含delete=$row[age],所以你需要使用$_GET['delete'],而不是$_GET['age']

您还应该使用准备好的语句来防止 SQL 注入。

$age = $_GET['delete'];

$stmt = mysqli_prepare($link,"delete from info where age = ?");
mysqli_stmt_bind_param($stmt, "i", $age);
$delete = mysqli_stmt_execute($stmt);

推荐阅读