我尝试使用php函数更新MySQL数据库表(在线),但每次点击“按钮更新”它都会回答我:
无法更新数据:'where子句'中的未知列'$ username'
有人可以帮我解决这个错误,或者只是建议我解决它的正确方法吗?
这是代码:
<html>
<head>
<title>Update Name of my_table in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['update']))
{
$dbhost = 'localhost';
$dbuser = 'dbuser';
$dbpass = 'dbpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$username = $_POST['username'];
$name = $_POST['name'];
$sql = 'UPDATE tbl_user SET name = $name WHERE username = $username';
mysql_select_db('my_table');
$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">Usrename</td>
<td><input name="username" type="text" id="username"></td>
</tr>
<tr>
<td width="100">Name</td>
<td><input name="name" type="text" id="name"></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>
这是my_table专栏:
id | username | password | email | name
答案 0 :(得分:3)
更改此查询行您在变量周围缺少单引号。
$sql = 'UPDATE tbl_user SET name = $name WHERE username = $username';
到这个
$sql = "UPDATE tbl_user SET name = '$name' WHERE username = '$username'";
答案 1 :(得分:1)
$sql="UPDATE tbl_user SET name = '".$name."' WHERE username = '".$username."'"
我认为有引用问题所以这会更好用,因为name和username字段包含字符串。使用字符串
时,查询字符串是更好的解决方案