I’m writing a piece of code that allows users to send messages to each other. Whenever I try to insert the message into the database, I get a syntax error, but I, for the life of me, cannot figure out what my error is. I know that the issue is not within connect.php. Also, I am getting the appropriate values for $from, $to, and $message so that can’t be the issue. Here is my code:
session_start();
require_once('../setup/connect.php');
$from = $_SESSION['id'];
$to = $_REQUEST['id'];
$message = trim($_POST['msg_body']);
$insert = "INSERT INTO messages(to, from, msg) VALUES('$to', '$from', '$message')";
mysql_query($insert) or die(mysql_error());
header("Location: view_profile.php?id=$to");
Here is the report mysql_error() generates:
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 ‘to, from, msg) VALUES(‘7’, ‘6’, ‘Hey how are you?’)’ at line
1
And here is an image of my database structure:
I appreciate any help!
TOandFROMare reserved keywords, it must be escaped with backtickIf you have time or privilege to alter, don’t use such names that are present on the reserved keyword list. It will give you future head aches.
As a sidenote, the query is vulnerable with
SQL Injectionif the value(s) came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.