Php mysql 数据查询更新给出语法错误

Php mysql query update of data gives syntax error

这是我的 php 代码,用于更新数据库中的产品:

$sql="UPDATE product SET name=$newname , price=$price , stock=$stock , color=$color WHERE id=$id";
if($conn->query($sql)){
    echo "product update";
}

它给出了这个错误:

Error: UPDATE product SET name=samsung galaxy note 20 ultra , price=40000 , stock=5 , color=white WHERE id=1
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'galaxy note 20 ultra , price=40000 , stock=5 , color=white WHERE id=1' at line 1

此代码应该有效:

$sql="UPDATE product SET name='$newname', price='$price', stock='$stock', color='$color' WHERE id='$id';";

但更好的方法是使用参数化准备语句,因为您现在很容易受到 SQL 注入攻击。另请参阅:https://dev.mysql.com/doc/apis-php/en/apis-php-mysqli.quickstart.prepared-statements.html

将单引号引到具有像这样的字符串值的变量

$sql="UPDATE product SET name='$newname' , price='$price' , stock=$stock , color='$color' WHERE id=$id";