简体   繁体   中英

PHP SQL Syntax error adding to table 1 with table 2 value

I get an error when running this php code which going to add value to table 1 based on table 2 value where table 3 value equal to 0

MY TABLE

------------------------------
id| table 1| table 2 | table 3|
-------------------------------
01| 100    | 10     | 0      |

PHP CODE

<?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);
    ?>

It said that I have error in my sql syntax

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

How to achieve this with the correct sql syntax?

You forgot the SET directive and your column names do not match those in your query, for which you'd have to use back ticks -

 $sql = "UPDATE `table` SET `table 1` = `table 1` + `table 2` WHERE `table 3` = 0";

You really should learn about prepared statements

I'm assuming the table and field names are aliases. Try this...

$sql = "UPDATE `table` SET `table 1` = `table 1` + `table 2` WHERE `table 3` = 0";

You need SET for an UPDATE statement, and fields or tables with spaces in the names need to be surrounded by the backtick character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM