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.
Related
One of my columns is called from. I can't change the name because I didn't make it.
Am I allowed to do something like SELECT from FROM TableName or is there a special syntax to avoid the SQL Server being confused?
Wrap the column name in brackets like so, from becomes [from].
select [from] from table;
It is also possible to use the following (useful when querying multiple tables):
select table.[from] from table;
If it had been in PostgreSQL, use double quotes around the name, like:
select "from" from "table";
Note: Internally PostgreSQL automatically converts all unquoted commands and parameters to lower case. That have the effect that commands and identifiers aren't case sensitive. sEleCt * from tAblE; is interpreted as select * from table;. However, parameters inside double quotes are used as is, and therefore ARE case sensitive: select * from "table"; and select * from "Table"; gets the result from two different tables.
These are the two ways to do it:
Use back quote as here:
SELECT `from` FROM TableName
You can mention with table name as:
SELECT TableName.from FROM TableName
While you are doing it - alias it as something else (or better yet, use a view or an SP and deprecate the old direct access method).
SELECT [from] AS TransferFrom -- Or something else more suitable
FROM TableName
Your question seems to be well answered here, but I just want to add one more comment to this subject.
Those designing the database should be well aware of the reserved keywords and avoid using them. If you discover someone using it, inform them about it (in a polite way). The keyword here is reserved word.
More information:
"Reserved keywords should not be used
as object names. Databases upgraded
from earlier versions of SQL Server
may contain identifiers that include
words not reserved in the earlier
version, but that are reserved words
for the current version of SQL Server.
You can refer to the object by using
delimited identifiers until the name
can be changed."
http://msdn.microsoft.com/en-us/library/ms176027.aspx
and
"If your database does contain names
that match reserved keywords, you must
use delimited identifiers when you
refer to those objects. For more
information, see Identifiers (DMX)."
http://msdn.microsoft.com/en-us/library/ms132178.aspx
In Apache Drill, use backquotes:
select `from` from table;
If you ARE using SQL Server, you can just simply wrap the square brackets around the column or table name.
select [select]
from [table]
I have also faced this issue.
And the solution for this is to put [Column_Name] like this in the query.
string query= "Select [Name],[Email] from Person";
So it will work perfectly well.
Hi I work on Teradata systems that is completely ANSI compliant. Use double quotes " " to name such columns.
E.g. type is a SQL reserved keyword, and when used within quotes, type is treated as a user specified name.
See below code example:
CREATE TABLE alpha1
AS
(
SEL
product1
type_of_product AS "type"
FROM beta1
) WITH DATA
PRIMARY INDEX (product1)
--type is a SQL reserved keyword
TYPE
--see? now to retrieve the column you would use:
SEL "type" FROM alpha1
I ran in the same issue when trying to update a column which name was a keyword. The solution above didn't help me. I solved it out by simply specifying the name of the table like this:
UPDATE `survey`
SET survey.values='yes,no'
WHERE (question='Did you agree?')
The following will work perfectly:
SELECT DISTINCT table.from AS a FROM table
Some solid answers—but the most-upvoted one is parochial, only dealing with SQL Server. In summary:
If you have source control, the best solution is to stick to the rules, and avoid using reserved words. This list has been around for ages, and covers most of the peculiarities. One tip is that reserved words are rarely plural—so you're usually safe using plural names. Exceptions are DIAGNOSTICS, SCHEMAS, OCTETS, OFFSETS, OPTIONS, VALUES, PARAMETERS, PRIVILEGES and also verb-like words that also appear plural: OVERLAPS, READS, RETURNS, TRANSFORMS.
Many of us don't have the luxury of changing the field names. There, you'll need to know the details of the RDBM you're accessing:
For SQL Server use [square_braces] around the name. This works in an ODBC connection too.
For MySQL use `back_ticks`.
Postgres, Oracle and several other RDBMs will apparently allow "double_quotes" to be used.
Dotting the offending word onto the table name may also work.
You can put your column name in bracket like:
Select [from] from < ur_tablename>
Or
Put in a temprary table then use as you like.
Example:
Declare #temp_table table(temp_from varchar(max))
Insert into #temp_table
Select * from your_tablename
Here I just assume that your_tablename contains only one column (i.e. from).
In MySQL, alternatively to using back quotes (`), you can use the UI to alter column names. Right click the table > Alter table > Edit the column name that contains sql keyword > Commit.
select [from] from <table>
As a note, the above does not work in MySQL
Judging from the answers here and my own experience. The only acceptable answer, if you're planning on being portable is don't use SQL keywords for table, column, or other names.
All these answers work in the various databases but apparently a lot don't support the ANSI solution.
Simple solution
Lets say the column name is from ; So the column name in query can be referred by table alias
Select * from user u where u.from="US"
In Oracle SQL Developer, pl/sql you can do this with double quotes but if you use double quotes you must type the column names in upper case. For example, SELECT "FROM" FROM MY_TABLE
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.
I banged my head against the wall for hours trying to understand why I could not complete an OOP insert statement into a MySQL insert table.
In my table I had a column named keys which was not getting inserted into.
I tried a lot of solutions, but then i renamed the column and the error sorted itself out.
Can anybody please tell me why this is occuring?
I am using wampserver 2.4.
It's a reserved word. You have to backtick it if you want to use it:
Like this:
insert into `keys` values (val1, val2) etc...
It's a mysql reserved word. You have to enclose it within ` to use it as column name. But I discourage that, troubles might appear anyway, for example with some libraries.
when your using reserved words you should enclose them inside backtick
for example `keys`
Without getting into the lengthy details of why, I have a need to auto-generate mySQL tables that utilize a unique table name that incorporates the string generated by PHP uniqid function. When doing so, I occasionally (not always) get the following query error:
Invalid query: 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 ''512e1d9518d44_tbl'' at line 1 Whole query: SELECT
SUM(p_count) AS 'pcnt' FROM 512e1d9518d44_tbl
I know I could use a simple cross reference lookup table, but is there another way to avoid the error, which I believe is the result of a violation of table naming rules, while still maintaining the table naming non-squential uniqueness? I've tried single quoting the table name but get the same result btw.
When your table / column name starts with a number, you have to escape it using backticks:
SELECT SUM(p_count) AS pcnt FROM `512e1d9518d44_tbl`
INSERT INTO expense (date,desc,price,out,method)
VALUES ('$time','$desc','$price','$out','$method');
What is wrong in the MySQL statement above? I have checked all the other stuff in my code but only this seems to be buggy.
I am passing this statement to mysql_query() function in PHP. It gives me an error and does not insert the data in the row.
All the variables above are also present.
So what could be the problem?
desc is keyword in SQL (order by `key` desc). You cannot use barewords which are also keywords in SQL. In this case, you should escape desc with ` symbol (like `desc`). date is also keyword, but MySQL decided to allow it's incorrect usage because of common usage before making it keyword. But not every database engine allows this, so be careful.
But, it's good practice to actually quote all keys, even if it's not needed - this way you could protect against adding keywords in SQL which would break your queries.
ORDER BY
List of keywords (in MySQL)
'date' is a MySQL keyword (for the date field type). You should enclose the field name with backticks like this:
INSERT INTO expense (`date`,desc,price,out,method)
(I think the other fields are fine, but you could add backticks to those as well if you like)