运行此 php 代码时出现错误,该代码将根据表 2 值向表 1 添加值,其中表 3 值等于 0
我的 table
------------------------------
id| table 1| table 2 | table 3|
-------------------------------
01| 100 | 10 | 0 |
PHP 代码
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$dbname = "lol";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE table table1 = table1 + table2 WHERE table 3 = 0";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
它说我的sql语法有错误
Error updating record: 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 '= table1 + table2 WHERE table3 = 0' at line 1
如何使用正确的 sql 语法实现此目的?
最佳答案
您忘记了 SET
指令,并且您的列名称与查询中的名称不匹配,为此您必须使用反引号 -
$sql = "UPDATE `table` SET `table 1` = `table 1` + `table 2` WHERE `table 3` = 0";
你真的应该了解prepared statements
关于使用表 2 值添加到表 1 时出现 PHP SQL 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31253718/