Wednesday, 7 June 2017

php - SQL error inserting into table



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 . "
" . $conn->error;
}


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...