无法更新数据:您的SQL语法中有错误;

时间:2014-04-07 07:54:57

标签: php html mysql

我有这个问题

错误

Could not update data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ..... line 1.

这是代码

<html>
<head>
<title>Update a Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['update']))
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db     = 'catalog';
$conn = mysql_connect($dbhost, $dbuser, $dbpass,$db);
if(! $conn )
{
 die('Could not connect: ' . mysql_error());
}

$adresa_e = $_POST['ADRESAE'];
$nr_matricol = $_POST['NR_MATRICOL'];

$sql = "UPDATE elevi ".
      "SET ADRESAE = $adresa_e ".
      "WHERE NR_MATRICOL = $nr_matricol" ;

mysql_select_db('catalog');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
 die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
  <table width="400" border="0" cellspacing="1" cellpadding="2">
    <tr>
      <td width="100">ADRESA ELEV</td>
      <td><input name="ADRESAE" type="text" id="ADRESAE"></td>
    </tr>
    <tr>
      <td width="100">NR MATRICOL</td>
      <td><input name="NR_MATRICOL" type="text" id="NR_MATRICOL"></td>
    </tr>
    <tr>
      <td width="100"></td>
      <td></td>
    </tr>
    <tr>
      <td width="100"></td>
      <td><input name="update" type="submit" id="update" value="Update"></td>
    </tr>
  </table>
</form>
<?php
}
?>
</body>
</html>

4 个答案:

答案 0 :(得分:1)

更改

$sql = "UPDATE elevi ".
      "SET ADRESAE = $adresa_e ".
      "WHERE NR_MATRICOL = $nr_matricol" ;

$sql = "UPDATE elevi SET ADRESAE = '$adresa_e' WHERE NR_MATRICOL = '$nr_matricol'" ;

答案 1 :(得分:0)

代码:

$conn = mysql_connect($dbhost, $dbuser, $dbpass,$db);
if(! $conn )
{
 die('Could not connect: ' . mysql_error());
}

将此代码更改为:

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
 die('Could not connect: ' . mysql_error());
}
mysql_select_db($db);

守则:

$sql = "UPDATE elevi ".
      "SET ADRESAE = $adresa_e ".
      "WHERE NR_MATRICOL = $nr_matricol" ;

将此代码更改为:

$sql = "UPDATE elevi ".
      "SET ADRESAE = '$adresa_e' ".
      "WHERE NR_MATRICOL = '$nr_matricol'" ;

答案 2 :(得分:0)

变量在请求中被视为简单文本:

试试这个

$sql = "UPDATE elevi SET ADRESAE = '".$adresa_e."' WHERE NR_MATRICOL = '".$nr_matricol."'" ;

答案 3 :(得分:0)

您需要运行以下代码

"UPDATE elevi SET ADRESAE = '$adresa_e' WHERE NR_MATRICOL = '$nr_matricol'" ;

当您使用mysql_connect时,请记住逃避您的字符串,从您的代码中我可以拥有您的网站并获取您的用户列表。

mysql_real_escape_string

在旁注上标准mysql_connect已达到其生命的终点(打开严格的PHP以查看有关此内容的所有警告)使用mysqli或PDO。

可以找到一个有用的示例here