SQL syntax error - mysql

I cannot find the error in the following sql:
$query = "INSERT INTO users('username', 'password', 'key', 'email', 'rank',
'ip','active') VALUES ('$username','$password','$random','$email','1','$ip',
'0')";
For some reason I keep getting the error
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 ''username', 'password', 'key', 'email', 'rank', 'ip', 'active') VALUES ('wx','79' at line 1

transform
('username', 'password', 'key', 'email', 'rank', 'ip', 'active')
to
(`username`, `password`, `key`, `email`, `rank`, `ip`, `active`)
In MySQL, field names should either be un-quoted or backticked (enclosed in back-ticks or back quotes).
In MS SQL Server, field names should either be unquoted or enclosed in [square brackets].
Other SQL DBMS mostly follow the SQL standard, and field names should either be unquoted or enclosed in "double quotes", and are then called 'delimited identifiers'. Sometimes, you have to turn on delimited identifier handling (which is itself non-standard behaviour).

Lose the quotes around the column names.

Don't put the column names in single quotes:
$query = "INSERT INTO users(username, password, key, email, rank, ip, active)
VALUES ('$username','$password','$random','$email','1','$ip','0')";
We'll ignore the SQL injection problems for now. :-)

"right syntax to use near ''user..." is a good hint. You should drop the ' ' around the column names.

In addition to removing the apostrophes around the names as already has been mentioned, you may need to specify some of the names as identifiers if they are reserved keywords in your database provider.
For SQL Server you would use brackets to specify an identifier: [password], however from your error message it seems as you are using MySQL, which uses backticks (`) instead of brackets. (As this forum uses backticks for code blocks I haven't been able to write an example, but I think that you get it anyway.)
Depending on the data types in your table you may also have to remove apostrophes around some values. If for example rank is a numeric field, there should be no apostrophes around the number 1 in the values.

Judging from where the error occurred, you're not escaping the data before sending it to the database, and the third character in the password was an apostrophe (').
Depending on which MySQL API you're using, you'll want one of the following functions:
mysql_real_escape_string, mysqli_real_escape_string, or pdo_quote to escape each variable before passing it to the database.
Alternately, if you're using MySQLi or PDO, use prepared statements with bind parameters which does this for you.

Get rid of the single quotes around your field names.
The error message is giving you a hint to your problem.
check the manual that corresponds to
your MySQL server version for the
right syntax to use near ''username',
'password', 'key', ...

INSERT INTO users('username', ...
As pointed out by Itay, there is no need for single quotes here. If you want/need to use reserved words as names, you have to delimit them in something else, either:
`backticks`, the default MySQL way, or
"doublequotes", the standard ANSI SQL way supported by other databases.
It's not a bad idea to set the sql_mode of your connection (or the server default, if that wouldn't interfere with other applications) to allow ANSI_QUOTES, if you would like to use cross-DBMS-compatible code here.
('$username', ...
Oops! Unless you processed $username to escape it previously, you've just invited a lovely SQL injection security hole into your applications. See mysql_real_escape_string or, better, use parameterised queries to avoid this.

Related

when i will run this query it will give an 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 'specific) VALUES ('5.jpg','kids','anyone')' at line 1,,
My query is
$sql="INSERT INTO imagetable(image,name,specific) VALUES ('$dbimage','$dbname','dbspec')";
specific is a reserved word in MySQL. Either use backticks to escape it or use another name for your column.
INSERT INTO imagetable (image, name, `specific`)
VALUES ('$dbimage','$dbname','dbspec')
sql="INSERT INTO `imagetable` (`image`,`name`,`specific`) VALUES ('$dbimage','$dbname','dbspec')";
While not required, it is a good practice to surround your column names (and table names) with ` characters. This avoids issues with reserved words used by the SQL language.
The reason you are getting this issue is because "specific" is a reserved keyword by the SQL language. Think of it like trying to name a variable "if". Since the keyword "if" is reserved by the coding language, you cannot do this. It is the same concept with "specific" in SQL.

Mysql handling with single quotes conflict

I'm using joomla to develop sites, but I'm having a strange error. I have a syntax error in the following code:
$q = "TRUNCATE TABLE ".$db->quote('#__csvi_available_fields');
Which give output on runtime:
TRUNCATE TABLE 'erx_csvi_available_fields'
But mysql shows an error:
JDatabaseMySQL::query: 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 ''#__csvi_available_fields'' at line 1
SQL=TRUNCATE TABLE '#__csvi_available_fields'
The strange thing is when I run without quotes, it runs normal:
TRUNCATE TABLE erx_csvi_available_fields <-- works without problem
Any idea what went wrong here ?
As other have said the wrong quotes have been added.
When using Joomla's JDatabase to provide quoting there are two different functions you can call one for values and another for database, table or column/field names.
To make your example line work you need to use quoteName() as follows:
$q = "TRUNCATE TABLE ".$db->quoteName('#__csvi_available_fields');
The $db->quote() is used to quote values being used in the SQL.
You can read through /libraries/joomla/database/database.php for an idea of how the abstraction is supposed to work.
don't use single quotes "'". use "`" (left to the numbers on your keyboard). normal single quotes are for strings, same as double quotes
Single quotes are used for strings, you should use backticks for names.
From the MySQL manual:
The identifier quote character is the backtick (`)
Also have a look at this Stackoverflow question: Using backquote/backticks for mysql queries

Error in MySQL Query (Banned Word?)

I have an MySQL query, which returns an error message. I think it could be due to the word "out". Normally, I would just change the field name but I am working on some software that I am not used to and I don't know how much of a change that would be. So, I want to be sure if I have to.
Here is the query:
SELECT * FROM probid_bids WHERE auctionid=73 AND out=0 AND invalid=0
Here the error message:
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 'out=0 AND invalid=0' at line 1
OUT is indeed a reserved word. You can encase the column names in backticks to quote the names, and thus avoid this problem, like so:
SELECT * FROM probid_bids WHERE `auctionid`=73 AND `out`=0 AND `invalid`=0
OUT is a reserved word (it is used to specify the type of parameters -- IN, OUT, INOUT -- when creating procedures). Try enclosing it inside backticks (`).
The rules regarding how and when to quote the identifiers (table names, column names, etc) are described here.
Note: certain MySQL configurations allow you to use double quotes as well but this should be avoided; stick with using backticks to quote identifiers and single quotes to quote strings.
Escape the keys:
SELECT * FROM `probid_bids` WHERE `auctionid`=73 AND `out`=0 AND `invalid`=0

MySQL LONGTEXT doesn't accept an apostrophe '

I was building a portal for my college with posting messages option. Hence I used LONGTEXT to store the message in mysql. But somehow the LONGTEXT doesn't accept the apostrophe mark.
It gives following error whenever I post some sentence with apostrophe mark:
"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 's open singles
tournament, will Electrical be able to maintain their dominance o' at line 1"
PS: not in the escape string, but in <textarea>, if I input the apostrophe mark it gives the error!
Escape it with a backslash like
SELECT 'This is a escape \' quote test';
EDIT
If you are taking information directly from a web form and inserting it into a data base - this is a massive security risk. This is how SQL injection is done.
You have two problems.
You copied the value of the long text into your 'query' (presumably an INSERT or UPDATE statement, though it could simply be the value to compare with in a SELECT).
You did not notice that the first unescaped single quote after the opening quote terminates the string.
Given that you are using MySQL, I believe you have two options on escaping:
Standard SQL (applies to most, if not all, SQL DBMS): use two consecutive single quotes to insert one:
'''' -- Insert a string consisting of one single quote
'He said, "Don''t do that!"' -- A string containing a single quote
MySQL (may also be an option elsewhere, but not every SQL DBMS will recognize it): use a backslash to escape the single quote:
'\'' -- As above
'He said, "Don\'t do that!"' -- Also as above
There may also be functions you can use to do the escaping for you - depending on the host language you are using. However, the preferred way to get values into an SQL statement, especially ones that might contain random characters, is to use placeholders. The mechanics depend on the host language in which you are embedding the SQL, but the general idea is:
The raw SQL string looks like: INSERT INTO SomeTable VALUES(?, ?, ?);
You PREPARE the statement, more or less explicitly.
When you execute it, you provide the data as parameters to the EXECUTE.
Or, if it is a SELECT statement, you PREPARE it, you DECLARE a cursor for it, then you OPEN the cursor and provide the parameter values at that time.
In one SQL-based language (IBM Informix 4GL):
DEFINE a INTEGER, b DECIMAL(10,2), c VARCHAR(250)
LET a = 1
LET b = 99999999.99
LET c = 'He said, "Don''t do that!"'
PREPARE p1 FROM "INSERT INTO SomeTable(a,b,c) VALUES(?, ?, ?)"
EXECUTE p1 USING a, b, c
PREPARE p2 FROM "SELECT * FROM SomeTable WHERE c = ?"
DECLARE c2 CURSOR FOR p2
OPEN c2 USING c
Note that if you do not use placeholders, you have to be extremely careful not to fall into the SQL Injection trap.
use the backslash character to escape the string:
"Carlito\'s Ways"
You may need to unescape later, but PHP has a built-in function for that.
insert into customers(firstname, lastname)
values ('Bill', 'O\'Connor');
I'm assuming you need to escape your apostrophes with a backslash character (\), but it would also be intuitive to provide the SQL query that you attempted to execute in order for people to help you further.

SQL exception with 'from' as a column name

I have a table with a column named 'from'. I want to retrieve data from it and so I tried following query.
select title,from,grade from localcourses where title='new';
But I get following exception due to the column name 'from'.
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 'from,grade from localcourses where title='new'
How can I avoid this without renaming the column name? Thank you.
Try --
select `title`,`from`,`grade` from localcourses where `title`='new';
If you are running MySQL in standard (ANSI) mode, use double quotes to "escape" the keyword:
select title,
"from",
grade
from localcourses
where title='new';
If you are running MySQL in non-standard mode (which is still the default if I'm not mistaken), you need to use MySQL's dreaded "backticks:
select title,
`from`,
grade
from localcourses
where title='new';
On MySQL you can use the ` (back apostrophe -- to the left of the 1 key on your keyboard). Use
`from`.
I'll be the first to say it - you should avoid naming tables, columns, triggers, procedures, functions, etc with the names of reserved, action, and other commonly used words in sql and database engine syntax. It only creates confusion such is the case here.
Assuming Oracle try
select title,"from",grade from localcourses where title='new';
In mySQL, you need to enclose the from column in backtick character
select title,`from`,grade from localcourses where title='new'
I suspect the backtick character you are using is not the right one, I am not sure what type of keyboard you have, so it might not send the proper character in.
Try this instead.
select title,localcourses.from,grade from localcourses where title='new'
and see if that helps