无法更新数据:您的SQL语法中有错误;
问题描述:
i have this problem
error
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.
here is the code
<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
";
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>
答
Variables are treated like simple text in your request :
Try this
$sql = "UPDATE elevi SET ADRESAE = '".$adresa_e."' WHERE NR_MATRICOL = '".$nr_matricol."'" ;
答
Change
$sql = "UPDATE elevi ".
"SET ADRESAE = $adresa_e ".
"WHERE NR_MATRICOL = $nr_matricol" ;
to
$sql = "UPDATE elevi SET ADRESAE = '$adresa_e' WHERE NR_MATRICOL = '$nr_matricol'" ;
答
The code:
$conn = mysql_connect($dbhost, $dbuser, $dbpass,$db);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
Change this code to:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db);
The Code:
$sql = "UPDATE elevi ".
"SET ADRESAE = $adresa_e ".
"WHERE NR_MATRICOL = $nr_matricol" ;
Change this code to:
$sql = "UPDATE elevi ".
"SET ADRESAE = '$adresa_e' ".
"WHERE NR_MATRICOL = '$nr_matricol'" ;
答
You need to run the below instead
"UPDATE elevi SET ADRESAE = '$adresa_e' WHERE NR_MATRICOL = '$nr_matricol'" ;
As you are using mysql_connect remember to escape your strings, from you code I could have your site and get a list of your users.
mysql_real_escape_string
On a side note standard mysql_connect is reaching the end of its life (turn on strict PHP to see all the warnings about this) use either mysqli or PDO.
A helpfull example can be found here