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

时间:2014-08-21 12:34:14

标签: php html mysql phpmyadmin

我想将表单中的数据删除到数据库中。但是我的代码给了我一个错误"无法删除数据:你的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第1行和第34行的'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>

4 个答案:

答案 0 :(得分:0)

您的查询应该是:

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

答案 1 :(得分:0)

尝试

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

你在SQ​​L查询中错过了

答案 2 :(得分:0)

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

答案 3 :(得分:-1)

错误在于您可以阅读的SQL语法。

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

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

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

应该有用。