Reputation: 695
I am getting this error when trying to insert data into my database from my website:
Error: INSERT INTO newtask (new_category, new_department, new_required,
new_name, new_address, new_contact, new_email, new_logged, new_description)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
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 '?, ?, ?, ?, ?, ?, ?,
?,
?)' at line 1
Here is my code:
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'tasks_db';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO newtask (new_category, new_department, new_required,
new_name, new_address, new_contact, new_email, new_logged, new_description)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Not sure what i am doing wrong here?
Upvotes: 1
Views: 164
Reputation: 211610
This is a prepared statement, so you need to prepare it, bind your values, and then execute it:
$stmt = $conn->prepare("INSERT INTO newtask (new_category, new_department, new_required,
new_name, new_address, new_contact, new_email, new_logged, new_description)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
// One "s" per placeholder value, plus one value per "s" after
$stmt->bind_param("sssssssss", $new_category, $new_department, ...);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Where $new_category
is whatever value is going into that column and so on.
This is all covered in the documentation.
The mistake is you were trying to run a SQL query with placeholder values and no data. ?
is not a valid value in MySQL. It's replaced at the driver level by the bind_param
operation on statements produced with prepare
. The query
function executes code as-is with no changes.
Upvotes: 3