Lee Ginger-Ninja McCarthy Lee Ginger-Ninja McCarthy - 1 year ago 36
SQL Question

MYSQL INSERT INTO Produces An Error: You have an error in your SQL syntax

I am trying to make a simple shoutbox for a school project.

Everything seems to be working fine, except when i try and send a message. My sql query is simple, but seems to not be working for some reason.



$sql = "SELECT * FROM shoutbox";
$result = mysql_query($sql);

echo '<table border=1>';
while($rows = mysql_fetch_assoc($result)){
$sb_username = $rows['username'];
$sb_message = $rows['message'];
$sb_sent_time = $rows['sent_time'];
echo '<tr><td>' . $sb_username . ': </td><td>' . $sb_message;
echo '</table>';
<form method=post action=shoutbox.php>
<input type=text name="message">
<input type=submit value="Send!">

$date = time();
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = $_SESSION['user_name'];
$sql = "INSERT INTO shoutbox ('username', 'message', 'time_sent') VALUES ('$username', '$message', '$date')";
mysql_query($sql) or die(mysql_error());


Produces the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''username', 'message', 'time_sent') VALUES ('c4sper', 'hello', '1461107151')' at line 1

Answer Source

Replace the following line in your code with this new one:

 $sql = "INSERT INTO shoutbox (`username`, `message`, 'time_sent') VALUES ('$username', '$message', '$date')";

Note : Use `` (Backticks) instead of '' (Quotes) around your table column's (fields) names in your INSERT query.

For detailed guidance,Take a look at :

When to use single quotes, double quotes, and backticks?