MySql + InnoDB + PHP Single Quote Discrimination? - php

Okay, I've recently converted a number of tables to the InnoDB storage engine and I've been getting errors whenever I use a single-quote ' in the column list of the INSERT statement:
INSERT INTO 'Table' ('Col1', 'Col2') VALUES ('Val1', 'Val2')
When I tired using phpMyAdmin to generate a proper statement, it looked virtually the same, so I pasted it in my app, and it worked. Then my next statement had the same error so I started to get suspicious. After a bit of playing around I found that the problem was that the query needed a back-tick instead of single-quotes, but not for the whole thing.
INSERT INTO `Table` (`Col1`, `Col2`) VALUES ('Val1', 'Val2')
works, so it's not like MySql doesn't understand the single-quote. What is going on here? I also can't just leave the columns unquoted like before with MyISAM (ie: Table(Col1, Col2))

That's because single quotes denote string literals, whereas backticks denote database/table/column identifier escapes.
Removing backticks causes an error because TABLE is a reserved word, so in order to use it as a table name you have to include backticks.

You put single quotes around string values, and you use backticks around object names. The backticks are technically not necessary though unless that name of your table/column is a reserved word or has spaces/funny characters in it.

Related

INSERT INTO wrong syntax with keyword named columns

Im currently working on a simple taskplanner in PHP (with Yii).
I submit my queries with
Yii::$app->db->createCommand(...)->execute();
, because I need to reformat the dates I get I can't use
$model->save();
If I want to execute the SQL-String it tells me:" You have an error in your SQL syntax"
A final generated SQL-String looks like:
INSERT INTO 'date_entry' (uid, `from`, `to`, entrydate, type)
VALUES
('62', '2016-04-17 12:04:00', '2016-04-24 12:04:00', '2016-04-13 10:04:33', '1');
I tried to escape the keywords from and to in "" , [] and ``.
If I run it by query I get the same error and by now I feel dumb...
Hope you can help me, thanks :)
I believe its due to the single quotes wrapping the table name
INSERT INTO `date_entry` (uid, `from`, `to`, entrydate, type)
VALUES ('62', '2016-04-17 12:04:00', '2016-04-24 12:04:00', '2016-04-13 10:04:33', '1');
Single quotes are used for strings, backticks/brackets/double quotes depending on the DBMS are used for reserved words, which I assume was your intention.Although I doubt date_entry is a reserved word, so no need for anything wrapping it.
For mysql you should use backticks (`) instead of single quotes (') for the table name:
INSERT INTO `date_entry` (uid, `from`, `to`, entrydate, type)
For consistency you should also quote all the field names.
Also as mentioned, you can use $model->beforeSave() to format the dates before saving. This, though, should be another question.

Are quotes around tables and columns in a MySQL query really necessary?

I have a short question about mysql query.
What is correct?
SELECT * FROM Persons WHERE Year='1965'
Or
SELECT * FROM `Persons` WHERE `Year` = '1965'
Is this a personal choice or is this something what is really wrong?
Quotes are needed if your identifiers (column, table names, operators, etc.) contain MySQL reserved words.
See here for the complete list of reserved words: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Both are correct, but the second one will ALWAYS be accepted, even when you use keywords or functions like while and NOW() that would normally be seen as operators.
What if you have a table named table, or a column named where. These are reserved keywords. If you used those in your queries without backticks, they'd produce an invalid query (Of course, using reserved keywords is bad practice).
SELECT something FROM table WHERE where = 1;
vs.
SELECT something FROM `table` WHERE `where` = 1;
Both methods are correct, the single quotation mark indicates starts and endings of a string.
Therefore if you for example use a column alias with a space like Birth year then you will need to use the single quotation mark like this;
... WHERE `Birth year` = `1965`
However it is not recommended only use more then one word in the aliases.
And as #Cody Caughlan said also when you use MySQL reserved words.

sql fulltext returning null

I'm using the joomla CMS to write to my db and have written a custom front end.
I'm trying to obtain the contents of the 'fulltext' row. I've tried mysql_fetch_assoc['fulltext'] and mysql_result($sql, 0, 'fulltext'). Both return fulltext. Here's the query string:
SELECT created, modified, title, introtext, 'fulltext', state, urls, created_by
FROM table_content
WHERE id='$id'
It's probably something really obvious I've missed because fulltext seems to conflict with sql without the quotation marks around it.
Any assistance would as always be appreciated!
You can use SQL keywords as field names, with appropriate escaping with backticks. You're using single quotes, which turns the word into a string that contains the word "fulltext".
Try
SELECT .... introtext, `fulltext`, state, ...
^--------^--- backticks
instead.

SQL Query Help—Confused About Quotes and Concatenating

I'm trying to wrap my head around writing queries in SQL and I'm having some difficulty understanding this example that I've found.
$q = "INSERT INTO `dbUsers` (`username`,`password`,`email`) "
."VALUES ('".$_POST["username"]."', "
."PASSWORD('".$_POST["password"]."'), "
."'".$_POST["email"]."')";
I guess I'm stumbling over the use of double quotes, single quotes, and the back-ticks. I compared this statement to the example on the W3 website and am just really confused as it seems much more complicated. Could you please explain to me what is going on in the above query? Thank you for your help!
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
The double quotes are used to define the elements that build your $q string. The single quotes identify strings within the SQL query that you are building and the backticks are used to escape object names in MySQL.
The double quotes surround the strings that will be a part of the query string. The dots between each double-quoted section are the concatenation operator. They are joining individual string pieces together.
You'll notice that there is a double-quote and dot before every $_POST[] array variable, and a dot and double-quote after.
e.g. " . $_POST["username"] . "
The first double quote ends the previous string section. The one at the end starts the next string section. Everything between the two dots is the POST variable. The reason the dots are necessary is because of the quotes around "username". In your W3 version they did not use quotes around the $_POST[] array key string (e.g. $_POST[firstname] and not $_POST["firstname"] or $_POST['firstname']) and so they did not need to use dots and quotes.
If you want to keep things simple, don't use the quotes inside of the $_POST[] variables and you won't have to use all those dots and quotes around them.
If you try version 1 without the dots and quotes the php parser will fail and you will see an error.
Backticks ` are to escape MySQL keywords (usually used for table and column names). Single or double quotes are required around any strings which are inserted.
Note that you should call mysql_real_escape_string on any string you're concatenating into a SQL query. Otherwise, it's possible to break out of quotes if $_POST also includes quotes. This can potentially be used to allow the execution of arbitrary SQL commands in what is known as a SQL injection attack.
The `back ticks` are optionally used to quote mysql field names, you will need them if you accidentally use one of mysqls reserved words to name a field - otherwise you don't need them.
When you enter a string into a field you have to 'quote it'.
The whole statement has to be quoted, but not clash with 2) above, hence the use of "double quotes".
Non scalar values such as arrays do not automatically expand, so you have to "drop out" . and . "back in" to PHP to build your string using concatenation sign a dot .
The backticks are a MySQL artifact in case you are using reserved words as your table/field names, and the single quotes delineate string literals in SQL. The double quotes are PHP-specific and separate strings in PHP. So, your query below would look like the following:
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('".$_POST["firstname"]."','".$_POST["lastname"]."','".$_POST["age"]."')";
One thing that the author above is doing is also breaking the PHP string into separate strings, probably to improve readability. MySQL server doesn't care about that.
There's actually a lot of unnecessary stuff in that first query. There are best practices to take into account but it could be re-written as such:
$q = "INSERT INTO dbUsers (username, password, email)
VALUES ('".$_POST["username"]."',
PASSWORD('".$_POST["password"]."'),
'".$_POST["email"]."')";
First thing: INSERT INTO dbUsers:
All this is doing is telling us what table we're inserting our data into.
(username, password, email)
Specifying the columns we're inserting into (order specific)
VALUES ('".$_POST["username"]."', PASSWORD('".$_POST["password"]."'), '".$_POST["email"]."')
Our values to be inserted (dependent on the order of the columns), then a terminating semicolon.
If you re-write this with hard coded values rather than concatenation, it would look like:
VALUES ('myUserName', PASSWORD('myPassword'), 'myEmail')
All of that should be self explanitory. Each value is contained within single quotes (') as they are strings. Then the password value is passed through the MySQL function PASSWORD which hashed the password for security purposes.
The double quotes are part of the PHP code, telling it that the items inside the double quotes are strings. They're not part of the SQL being built.
The single quotes are used to surround values in the resulting SQL. Ie, you're telling the database the value "bob" is used here. For some types of value (integers, boolean, etc) you don't need the single quotes. For many others (varchar, dates, etc), you need the single quotes.
The backticks perform much the same function as single quotes, except they're used around table names, field names, etc... rather than around actual values. They're used when the name in question wouldn't be interpreted by the database correctly there, for example if you had a field named count, since that's a keyword in SQL. As noted elsewhere, the backticks aren't necessary in your example, but many people put them in all the time because it doesn't hurt to have them; as a safety net, kindof.
To give a visible, simpler example
$name = "bob";
$sql = "SELECT * FROM `mytable` WHERE `name` = '" . $name . "'";
This would result in the $sql variable being
SELECT * FROM `mytable` WHERE `name` = 'bob'
As you can see, the double quotes are not part of the string.. they're just used in creating it. In the resulting SQL, the backticks surround the table/field names, and the single quotes surround the actual value bob.
As a complete side note, using the POST values directly in created SQL is dangerous as it allows for SQL injection attacks. The values should be escaped or a parametrized query should be used.

How to properly escape a string via PHP and mysql

Can someone explain what is the difference between using mysql_real_escape_string on a string or wrapping `` around the column.
For example "insert into table (``column``) values ('$string')"
or
$escapestring = mysql_real_escape_string($string);
"insert into table (column) values ('$escapedstring')"
What is the difference between these two and what should I use? Thanks.
There's a difference between the backtick ` and the single quote '.
The backtick is intended to escape table and field names that may conflict with MySQL reserved words. If I had a field named date and a query like SELECT date FROM mytable I'd need to escape the use of date so that when MySQL parses the query, it will interpret my use of date as a field rather than the datatype date.
The single quote ' is intended for literal values, as in SELECT * FROM mytable WHERE somefield='somevalue'. If somevalue itself contains single quotes, then they need to be escaped to prevent premature closing of the quote literal.
Those two aren't related at all (as far I know anyway)
From the manual : http://php.net/manual/en/function.mysql-real-escape-string.php
Escapes special characters in the
unescaped_string, taking into account
the current character set of the
connection so that it is safe to place
it in a mysql_query().
So essentially what it does is, it will escape characters that are unsafe to go into mysql queries (that might break or malform the query)
So o'reily will become o\'reily

Categories