user3259244 user3259244 - 2 years ago 66
SQL Question

mySQL error, that I can't find

I'm writing because I simply can't find my error, I copied this code from another document and edited some few things, but then I have an error. I'm unable to see what it is.

The following error is:

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 'by,telefon,email) VALUES (987, , , , by, , )' at line 1

And my code is following:

$taelf = mysql_result(mysql_query("SELECT COUNT(*) FROM `Firma` WHERE `navn` = '$navn'"),0);
if($taelf < 1){
mysql_query("INSERT INTO `Firma` (navn,cvr,Adresse,postnr,by,telefon,email)
VALUES ($_POST[navn], $_POST[cvr],
$_POST[adresse], $_POST[postnr],
by, $_POST[nummer], $_POST[email]
) or die(mysql_error());
echo "<div id='success'>Vupti, firmaet er nu oprettet. '$_POST[navn]','$_POST[cvr]','$_POST[adresse]','$_POST[by]','$_POST[postnr]','$_POST[nummer]','$_POST[email]'</div>";

Answer Source

BY is a reserved word. If you are going to name a column with that name you must wrap it in ticks:

INSERT INTO `Firma` (navn,cvr,Adresse,postnr,`by`,telefon,email) 

Also see Fabien Warniez's answer which explains that you also need to wrap your string values in quotes.

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial. You are also wide open to SQL injections

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download