This question already has an answer here:
I'm creating an admin panel with a form that creates a blog post. When I try to insert this into the database, I'm getting an error. This is my SQL statement:
INSERT INTO blog_posts ('title', 'author', 'tags', 'category', 'body') VALUES ('$title', '$author', '$tags', '$category', '$body');
What am I doing wrong? Full code:
$servername = "host";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$title = $_POST['title'];
$author = $_POST['author'];
$tags = $_POST['tags'];
$category = $_POST['category'];
$body = $_POST['editor1'];
// sql to insert a record
$sql = "INSERT INTO blog_posts ('title', 'author', 'tags', 'category', 'body') VALUES ('$title', '$author', '$tags', '$category', '$body');";
if (mysqli_query($conn, $sql)) {
echo "Succes";
} else {
echo "Error";
}
mysqli_close($conn);
So, what do I do now?
</div>
Instead of:
$sql = "INSERT INTO blog_posts ('title', 'author', 'tags', 'category', 'body') VALUES ('$title', '$author', '$tags', '$category', '$body');";
Try this
$sql = "INSERT INTO blog_posts (`title`, `author`, `tags`, `category`, `body`) VALUES ('$title', '$author', '$tags', '$category', '$body')";
One thing that is immediately obvious (as stated in comments), is your use of quotes around the field names, quotes are reserved for strings, not field/column names, so where you have;
INSERT INTO blog_posts ('title', 'author', 'tags', 'category', 'body') VALUES
Should instead be;
INSERT INTO blog_posts (`title`, `author`, `tags`, `category`, `body`) VALUES
The above uses backticks, you can discard these, but be aware of special words in MySQL
Also to note - you are wide open to SQL injection attacks, make use of prepared statements, these are best, but there are a couple of other options;
With this such as this, as per my comment, it is often appropriate (and helpful) to make use of some of the debugging tools provided to you.
In this instance, mysqli_error would have been of great use to you (and in turn us) as it gives quite a good indication of what went wrong / where