在php中删除表单中的数据到数据库中


delete data from a form into a database in php

我想从表单中删除数据到数据库中。但是我的代码给了我一个错误"无法删除数据:你有一个错误在你的SQL语法;查看与MySQL服务器版本对应的手册,以便在第1行'WHERE id = 3'附近使用正确的语法。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>

<!--$con=mysqli_connect("localhost","root","","firstphp");*/-->
<?php
if(isset($_POST['delete']))
{
$con=mysql_connect("localhost","root","");
if(!$con)
{
  die("Could not connect: " . mysql_error());
}
$id = $_POST["id"];
$sql = "DELETE employee ".
       "WHERE id = $id" ;
mysql_select_db('firstphp');
$result = mysql_query($sql,$con);
if(!$result)
{
  die("Could not delete data: " . mysql_error());
}
echo "Deleted data successfully'n";
mysql_close($con);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Employee ID</td>
<td><input name="id" type="text" id="id"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>

你的查询应该是:

$sql = "DELETE FROM employee WHERE id = $id" ;

Try

$sql = "DELETE FROM employee "."WHERE id = $id" ;

在sql查询

中错过了FROM
$sql = "DELETE FROM employee WHERE id =".$id ;

错误在于SQL语法,因为你可以读取。

$sql = "DELETE FROM employee ".
       "WHERE id = ".$id ;

如果' id '是一个VARCHAR,执行以下操作:

$sql = "DELETE FROM employee ".
       "WHERE id = '".$id."'";