1

I keep getting this error in my php. It worked fine when I hard set the values but doesn't seem to work with variables.

Error: INSERT INTO ContactUS (name, email, subscribed) VALUES (TEST, my@email.com, 1) 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 'Anis, my@email.com, 1)' at line 1

// Create connection
            $conn = new mysqli($servername, $username, $password, $dbname);
            // Check connection
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            } 

            $sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ($name, $email, $subscribed)";

            if ($conn->query($sql) === TRUE) {
                echo "New record created successfully";
            } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
Xorifelse
  • 7,878
  • 1
  • 27
  • 38
Luc
  • 60
  • 1
  • 9
  • `VALUES ('$name', '$email', '$subscribed')`, but this leaves open to sql injection. Read this [answer](http://stackoverflow.com/q/60174/711206). – Federkun Jan 19 '16 at 22:34

2 Answers2

1

Values should be quoted:

$sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ('$name', '$email', '$subscribed')";

Perhaps it's better to use prepared statements as this is done automatically for you and you won't be vulnerable to SQL injections.

Xorifelse
  • 7,878
  • 1
  • 27
  • 38
  • 1
    You should change your second sentence to `It is better to use prepared statements as this is done automatically for you, and you won't be open to SQL injections.` – chris85 Jan 19 '16 at 22:42
  • Ah thanks I assumed because they were variables they did not need quotes. – Luc Jan 19 '16 at 23:29
0

Use quotes around variables, as PHP will replace its value, leaving an invalid query:

 $sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ('$name', '$email', '$subscribed')";

but please use prepared statements, otherwise you'll be victim of SQL injection

Roberto
  • 2,115
  • 24
  • 32