1

我正在尝试使用下面的代码更新我的数据库中的记录。我正在尝试更改产品名称,但出现以下错误:

Could not update data: Unknown column 'Earrings' in 'field list'

代码:

<?php
if(isset($_POST['update']))
{
    $dbhost = 'databasehost';
    $dbuser = 'username';
    $dbpass = 'password';
    $conn = mysql_connect($dbhost, $dbuser, $dbpass);

        if(! $conn )
        {
            die('Could not connect: ' . mysql_error());
        }

        $ProductsID = $_POST['ProductsID'];
        $ProductsName = $_POST['ProductsName'];

        $sql = "UPDATE Products ".
           "SET ProductsName = $ProductsName ".
           "WHERE ProductsID = $ProductsID" ;

        mysql_select_db('databasename');
        $retval = mysql_query( $sql, $conn );
        if(! $retval )
        {
            die('Could not update data: ' . mysql_error());
        }
        echo "Updated data successfully\n";
        mysql_close($conn);
}
else
{
?>
4

4 回答 4

1

You want something like this:

ProductsName = '$ProductsName'

Also, be sure to escape that input, else you'll be subjected to SQL injections.

于 2013-04-27T09:51:48.233 回答
1

You are not sanitizing your data, so there is a good chance that your query could break depending on the value submitted, not to mention it leaves your database wide open for an attacker to manipulate via SQL Injection.

Please do not use mysql_ functions, as they are depricated. You should be using prepared statements, please see PDO and mysqli.

As for your answer, you need to put 'quotes' around the $variable

于 2013-04-27T09:52:37.347 回答
1

查询应该是

$sql = "UPDATE Products ".
       "SET ProductsName = '$ProductsName' ".
       "WHERE ProductsID = $ProductsID" ;

你忘了$ProductName用引号括起来。在处理字符串值时不要忘记这样做。

于 2013-04-27T09:53:14.100 回答
1

您正在尝试将 ProductsName 设置为现有列,添加引号以让 sql 解释值:

$sql = "UPDATE Products ".
       "SET ProductsName = '$ProductsName' ".
       "WHERE ProductsID = $ProductsID" ;
于 2013-04-27T09:56:11.367 回答