views:

63

answers:

3

What's wrong with this MySQL query?

$name = mysqli_real_escape_string($db,$_POST['name']);
$email = mysqli_real_escape_string($db,$_POST['email']);
$comment = mysqli_real_escape_string($db,$_POST['content']);
$dt = date("F j, Y, g:i a");
$sql = mysqli_query($db, "INSERT INTO `tbl_contact` (`id`, `name`, `email`, `comment`, `date`) 
VALUES (NULL, '".$name."', '".$email."', '".$comment."', '".$dt."'");

It keeps failing with

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 2.

Thanks :)

+6  A: 

You're not closing the VALUES parenthesis in your SQL - the last line should end like this:

..., '".$dt."')");
              ^
              Added closing parenthesis for the VALUES clause.
RichieHindle
thanks a million, this is what coding at night does to me :(
Shamil
+1  A: 

Indeed, you need to close the parenthesis.

Next time, if you get this type of error, try to find out which SQL is actually being executed by printing it. You can then either analyse the query by hand (you would've seen this one in a few seconds), or run it in some environment where you can easily modify and execute queries if the query is more complex.

Wouter van Nifterick
This is so important if you're working with dynamically generated SQL. It's nearly impossible to understand what's wrong without seeing the end result of your 20 concat statements
colithium
A: 

One of the good practices which I follow to avoid such pitfalls is to create a query in one line and execute the query in the next line like this

$sql="INSERT INTO `tbl_contact` (`id`, `name`, `email`, `comment`, `date`) 
VALUES (NULL, '".$name."', '".$email."', '".$comment."', '".$dt."')";

$result = mysqli_query($sql);

Another time saving trick is ommitting unnecessary concatenations for appending '. Your sql could have been more simpler like this

$sql="INSERT INTO `tbl_contact` (`id`, `name`, `email`, `comment`, `date`) 
VALUES (NULL, '$name', '$email', '$comment', '$dt')";
Saradhi