Why is this MySQL statement syntax wrong? - php

I am using prepared statements to process incoming post data, clean the array, and insert into a MySQL database.
Here is the SQL statement just before it is submitted:
INSERT INTO LoggedCarts (Bill-Address1,Bill-Address2,Bill-City,Bill-Company,Bill-Country,Bill-Email,Bill-Firstname,Bill-Lastname,Bill-Name,Bill-Phone,Bill-State,Bill-Zip,Card-Expiry,Card-Name,Card-Number,Comments,Date,ID,IP,Item-Code-1,Item-Count,Item-Description-1,Item-Id-1,Item-Quantity-1,Item-Taxable-1,Item-Thumb-1,Item-Unit-Price-1,Item-Url-1,Numeric-Time,Ship-Address1,Ship-Address2,Ship-City,Ship-Company,Ship-Country,Ship-Email,Ship-Firstname,Ship-Lastname,Ship-Name,Ship-Phone,Ship-State,Ship-Zip,Shipping,Space-Id,Store-Id,Store-Name,Tax-Charge,Total) VALUES ("Pineapple Highway","","Orange","","US United States","casedilla#hotmail.com","Bob","Dole","Bob Dole","9075554509","CA","97056","","Check","NumberTemporarilyUnavailable","","Tue Dec 10 16:55:11 2013 GMT","yhst-130408242826480-485","50.78.241.193","TERRALUX-TT-5","1","Terralux TT-5 LED Tactical Flashlight 650 Lumens Uses 2 x CR123 or 1 x 18650","terralux-tt-5","3","YES","","112.49","http://www.batteryjunction.com/terralux-tt-5.html","1386694511","Pineapple Highway","","Orange","","US United States","casedilla#hotmail.com","Bob","Dole","Bob Dole","9075554509","CA","97056","Air (3-5 days)","","yhst-130408242826480","BatteryJunction.com","0.00","337.47")
Question is, what is wrong with the syntax? The same code is also used for a different table that holds abandoned carts and it writes fine.
Note: As has been pointed out below, the use of hyphens in column names is frowned on, as it requires special preparation prior to submitting the query. In this instance, I am matching the column names to the incoming post data key array. I could have gone through and cleaned the key array, removing the hyphens, which would have been an alternative solution.
All in all, as suggested below, the correct solution to the question of why this SQL statement is failing is the use of special characters(hyphen) in the column name, resulting in the required use of a backtick around the column name(backtick = ` where as apostrophe = ') allowing the column name to be read unbroken.
Observing where the break occurred by testing the original statement in PHPMyAdmin:
#1064 - 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 '-Address1,Bill-Address2,Bill-City,Bill-Company,Bill-Country,Bill-Email,Bill-Firs' at line 1
did give a clue as to why the statement was failing.
Thanks for the help guys!

You need to escape column names with special characters with backticks. - is a special character. Use
INSERT INTO LoggedCarts (`Bill-Address1`, ...

If those field names really include minus signs, then they need to be enclosed in backticks:
`Bill-Address1`

Try inserting string values with single quotes instead.

Related

PHP insert into SQL statement with several parameters [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
i have a simple php INSERT INTO SQL statement that simply refuses to update several columns at once. i have no idea why but the following statement is acceptabel;
$sql = "INSERT INTO niceTable (first) VALUES ('Hello')";
however if i try to following
$sql = "INSERT INTO niceTable (first, last) VALUES ('Hello', 'You')";
it breaks down and throws the following error:
"Error updating record: 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 'desc) VALUES ('Hello', 'update')' at line 1"
I have checked the syntax, but it seems ok. I am using a one.com server. Anyone got any tips?
Your actual query (not the one in your question) seems different. The error message seems to have desc somewhere, which is a reserved word. If you use reserve words as column names (don't), you should enclose them in backticks:
INSERT INTO tbl (`order`, `desc`) VALUES ('foo', 'bar');
As per your "posted code":
The reason being that first and last are MySQL reserved words
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
and require special attention.
Either wrap them in ticks or rename them to something other than reserved keywords.
INSERT INTO niceTable (`first`, `last`)
Edit: However, your error doesn't support the issue here, nor the column name(s):
for the right syntax to use near 'desc)
this tells me you are using desc which is also another MySQL reserved word.
You should also use prepared statements
https://en.wikipedia.org/wiki/Prepared_statement
Plus, should your inputs contain characters that MySQL may complain about such as apostrophes John O'Neil then you will need to escape those values.
MySQL will interpret that as ('Hello', 'John O'Neil') in turn causing another syntax error.
Escaping it, would interpret it as ('Hello', 'John O\'Neil') making it valid.
I'm thinking ahead here.
Enclose your column names in backticks
Last is a function in MySQL
$sql = "INSERT INTO niceTable (`first`, `last`) VALUES ('Hello', 'You')";

Whats wrong with this sql?

I'm new to php and sql , so could you please help me by telling me how to fix this sql error.
The sql is below.
INSERT INTO xml-group (id,groupid,name,descriptor,cust_id)
VALUES (1,1,'other contacts','other contacts',16)
The 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 '-group (id,groupid,name,descriptor,cust_id) VALUES
('0','0','mobiles','mobile',1' at line 1
Many thanks
The - isn't allowed in an unquoted table name. Use backticks to quote xml-group:
INSERT INTO `xml-group` (id,groupid,name,descriptor,cust_id)
VALUES (1,1,'other contacts','other contacts',16)
Btw, in a well designed database schema you might avoid such names and use _ instead.
use backticks arround table name it causes GROUP a special keyword of mysql
INSERT INTO `xml-group` (id,groupid,name,descriptor,cust_id)
VALUES (1,1,'other contacts','other contacts',16)
"-" Hyphen is not allowed in SQL syntax.
use backticks (`) symbol to escape it.
Also, if field ID is an auto-number field, primary index and "1" is already assigned, you'll get an error. (Same with any other fields that require unique values...)
Two options to fix it:
Replace xml-group with xml_group
Include backticks around it such as `xml-group`
Personally I would do both of those above options, but you can get away with just one.
You are best to enforce the use of back ticks for a few reasons. The primary reason I use back ticks myself is:
You do not have to worry about clashing with reserved or future key words.
Other reasons, but often dependant on personal preference and coding standards you have/can enforce on the whole code base are:
You can easily search the entire project for the use of that specific table. If for example you did SELECT user FROM users there is a good chance you have method names, variables, comments etc all containing the word "user" making it hard to find all the queries containing a reference to the user table amongst so many false positives. However, if you enforce the use of back ticks you just have to search for `users` to find all queries referencing it along with fields (as long as you haven't abstract the queries to the point where they are built up at runtime like: "SELECT `$field` FROM `$table`").
It can help with clarity and readability as it visually separates keywords from variable values like field names and table names even if everything is in lower case.

Stumped on why MySQL won't accept my query?

Okay, so I'm currently using mysqli_real_escape_string to escape my SQL queries before sending them to MySQL via PHP. Yet, for some reason my queries aren't processing, and when I outputted the MySQL query and pasted it in to PHPMyAdmin, it gave the following error:
#1064 - 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 'WHERE ind={A$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQg' at line 1
Now, the following is my query:
INSERT INTO `db`.table(`colheader`) VALUES ('{\"hey\":[\"Hello world\",\"7\\/9\\/2013\"]}') WHERE ind='$6$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQgSnLHIlkBOtDTzu9AuZIZTr6GS4Rzr.iW11041994'
Now, I know that the string assigned to 'ind' has some issues, but I tried putting a slash before every period and every dollar sign and it still doesn't work. I tried putting the whole thing in double quotes, even brackets. Nothing. Could anyone point out what I'm clearly missing? I've looked at the documentation and can't seem to find anything. Thank you in advance!!
WHERE serves to filter which records will be affected or retrieved by your query, and INSERT servers to append a whole new record to a table.
An INSERT can never affect existing records, therefore its nonsense to have a WHERE clause. INSERT does not support WHERE.
If you are trying to edit the value of a field on an existing record, use UPDATE instead.
Take a look at the MySQL Reference Manual for details about its usage.
if your trying to make an update to the specified index use
UPDATE `db`.table SET `colheader` = '{\"hey\":[\"Hello world\",\"7\\/9\\/2013\"]}' WHERE ind='$6$RTkAIqah0J1N$Fqymnud9s5PwnWw2wC.Y02oDo4H3W8QJPoJ$6$KK8UearuUCDH$FQgSnLHIlkBOtDTzu9AuZIZTr6GS4Rzr.iW11041994'

MySQL - INSERT INTO says I have worng syntax with 'to'='$user2' [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 8 years ago.
$time=date("G:i:s j.n.Y");
$wholetime="$time";
mysql_query("INSERT INTO rivase_chat_posts SET sender='$user', content='$msg', time='$wholetime', 'to'='$affectuser'");
$msg="";
I am doing a private chat thing. That is my code. It results this error:
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'='gs'' at line 1 ($user="gskartwii", $msg="HI",
$affectuser='gs')
For column names, use backticks rather than single-quotes:
`to`='$affectuser'
Single quotes are there for strings only. Backticks (normally left of the number 1 on your keyboard) are the things to use for column or table names in mysql.
Edit: As Michael Berkowski correctly points out, the reason you have to do this for the column name is because to is a reserved word in mysql - which is a lovely way of saying that it is a special word that mysql sees to mean something within a query normally. on that note, it really might not be the best idea to use the reserved words as columns in your table - you will have to backtick them in every single instance that you use them. You might want to consider renaming it to something like toUser which will probably make the rest of your project easier to SQL out :)
You put the 'to' between single quotes. Column names are not quoted, or between backquotes. Single quotes are for strings. You cannot update a string, hence SET 'to'='user' is an error.
INSERT INTO rivase_chat_posts
SET `sender`='$user', `content`='$msg', `time`='$wholetime', `to`='$affectuser'
UPDATE: comments say to is a reserved word and should always be escaped - using backquotes.
To is a reserved word. Escape it:
INSERT INTO rivase_chat_posts
SET sender='$user', content='$msg', time='$wholetime', `to` ='$affectuser'

MySQL - Small query issue

I have a problem with a small query. When I execute it I am getting a error which 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 'key=stqq WHERE id=75' at line 1
My query is as follows
UPDATE roles SET name=stylistqq, key=stqq WHERE id=75
add quotes
UPDATE roles SET name='stylistqq', key='stqq' WHERE id=75
Are stylistqq and stqq strings? If so, they should have single quotes around them. Pekka's recommendation to use a different column name other than key is also a good idea. You can make MySQL take that string by putting backticks around it, but you'll always need them.

Categories