php - 无法删除php中的记录
问题描述
我创建了一个显示在网站上的数据库,也可以插入值。我试图删除记录。
这段代码是create.php
,它创建了一个带有name
age
、email
和num2
的表单cal
(cal 只是添加age
并num2
查看计算的工作原理)。我们插入值并显示有一个表的数据库信息,该表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
都被成功删除。但是,如果使用此代码,则不会发生任何事情。
解决方案
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);
推荐阅读
- c - GetSystemMetrics() 在 RDP 会话上报告错误的鼠标值
- java - Java 算术方程字符串 java min(x,y),max(x,y),+,-,/,*
- microsoft-graph-api - 电话号码使用 Users.ReadBasic.All 返回为 null
- python - 迭代地将新字符串添加为列表中的元素
- ruby-on-rails - 如何使用 devise gem 发送电子邮件?
- java - 在springboot angular8 webapp中验证和管理用户的最简单方法是什么?
- python - 如何将 IF 语句应用于 DataFrame?
- c# - 如何从字符串中删除空格和“\n”?
- node.js - 基于 WebSocket 服务器的 NodeJS XMPP
- python - 如何在没有 pip install 的情况下仅手动复制单个站点包?