使用表 2 值添加到表 1 时出现 PHP SQL 语法错误

标签 php mysql sql syntax error-handling

运行此 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/

相关文章:

php - 转换/下载视频 php 或 javascript

javascript - 在表单中动态添加数组文本框

mysql - 如何使用两个表和辅助表编写查询?

mysql - 我可以检索 mysql 中触发器影响的行/列吗?

javascript - window.open 不执行任何操作

php - 为什么 PHP 不包括我的文件,而它显然存在?

MYSQL 存储过程 - 无法创建过程

mysql - SQL select total 并分为成功和失败

sql - 在 Sequelize 后端查询中查找匹配对象

sql - 为什么 auto_increment "spelled"带有下划线?