0

There are similar questions about this but none of the solutions help me. Is there anyone who can tell the problem here?

This is my code

<?php
    // Create connection
    $conn = new mysqli("localhost", "root", "", "mydb");
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    for ($i=0; $i < 10; $i++) { 
        $dec = $i;
        $hex = dechex($dec);
        $sql = "
            INSERT INTO mytable (dec, hex)
            VALUES ('$dec', '$hex')
        ";
        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    }
    
    $conn->close();
?>

And this is the error I get:

Error: INSERT INTO mytable (dec, hex) VALUES (0, 0)

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 'dec, hex) VALUES (0, 0)' at line 1Error: INSERT INTO mytable (dec, hex) VALUES (1, 1)

O. Jones
  • 103,626
  • 17
  • 118
  • 172
rubinrot
  • 1
  • 1
  • 2
    https://en.wikipedia.org/wiki/SQL_reserved_words, `dec` is a MySQL reserved word. Backtick it, or rename the column. – jarlh Jun 14 '21 at 07:52
  • Print out the whole insert statement and check your query manually by executing it on dmbs directly. – Reporter Jun 14 '21 at 07:53
  • 2
    Side note: Do not use string interpolation or concatenation to get values into SQL queries. That's error prone and might make your program vulnerable to SQL injection attacks. Use parameterized queries. See ["How to include a PHP variable inside a MySQL statement"](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement) and ["How can I prevent SQL injection in PHP?"](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – sticky bit Jun 14 '21 at 07:56

0 Answers0