此代码是在 LAMP 堆栈上设置的。我在使用"删除"页面时遇到问题。PHP 中的 Delete 函数仅在 mysql 表中的条目是数字时才有效。无论条目如何,我都需要它来删除该行。电子邮件字段在 mysql 中设置为 "varchar(25)"。我没有在代码中定义变量,所以我不明白为什么它将其限制为数字。
这是页面:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="gradientbackground">
<table class="beachpictures" align="center" border="1">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Website</th>
<th>Gender</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
require 'project_db.php';
mysql_connect("$servername", "$username", "$password")or die("cannot connect");
mysql_select_db("$database")or die("cannot select DB");
//execute the SQL query and return records
if (!$result = mysql_query("SELECT * FROM $table"))
echo 'mysql error: ' .mysql_error();
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['Name']; ?></td>
<td><?php echo $row['Email']; ?></td>
<td><?php echo $row['Website']; ?></td>
<td><?php echo $row['Gender']; ?></td>
<td class="record-delete">
<form action='delete.php?Email="<?php echo $row['Email']; ?>"' method="post">
<input type="hidden" name="Email" value="<?php echo $row['Email']; ?>">
<input type="submit" name="submit" value="Delete">
</form>
</td>
</tr>
<?php }
?>
</tbody>
</table>
<br>
</div>
</body>
</html>
下面是执行实际查询的 delete.php 文件:
<?php
require 'project_db.php';
mysql_connect("$servername", "$username", "$password")or die("cannot connect");
mysql_select_db("$database")or die("cannot select DB");
//Define the query
$query = "DELETE FROM $table WHERE Email={$_POST['Email']} LIMIT 1";
//sends the query to delete the entry
mysql_query ($query);
if (mysql_affected_rows() > 0) {
//if it updated
?>
<strong>Record Has Been Deleted</strong><br /><br />
<?php
} else {
//if it failed
?>
<strong>Deletion Failed</strong><br /><br />
<?php
}
?>
您需要添加引号: 否则,mysql 将期望 $_POST['email'] 是一个数字。
另外,你应该切换到PDO或MySQLi,因为mysql_*
函数被弃用,并且你对SQL注入开放。所以你的代码应该是:
<?php
require 'project_db.php';
$connect = mysqli_connect($servername,$username,$password,$database)or die("cannot connect");
//Define the query
$query = "DELETE FROM $table WHERE Email='".mysqli_real_escape_string($connect,$_POST['Email'])."' LIMIT 1";
//sends the query to delete the entry
$execute = mysqli_query ($connect,$query);
if (mysqli_affected_rows($execute) > 0) {
//if it updated
?>
<strong>Record Has Been Deleted</strong><br /><br />
<?php
} else {
//if it failed
?>
<strong>Deletion Failed</strong><br /><br />
<?php
}
?>