Forgive me, I'm a beginner. The following code returns a parse error:
$query = "INSERT INTO scenario_needgames VALUES ("$id", "Battle of the Bulge")";
the query builder in phpMyAdmin gave me this slightly modified string that works:
$query = "INSERT INTO scenario_needgames VALUES (\"$id\" , \"Battle of the Bulge\");";
but I'm confused as to why the quotes need to be escaped when they're actually part of the query syntax, and not - say - part of a title or string? The introductory book I'm learning from doesn't include those for such simple strings.
The $id value is 7 digits, 4 letters and then 3 numbers if you're curious.
Thank you.
Double quotes need to be escaped within a double quoted string, alternatively you can use a single quoted string and not have to escape the double quotes, but then you cannot directly interpolate variables, you have to use concatenation instead:
$query = 'INSERT INTO scenario_needgames VALUES ("' . $id . '", "Battle of the Bulge")';
Alternatively, just replace your inner double-quotes with single-quotes:
$query = "INSERT INTO scenario_needgames VALUES ('$id', 'Battle of the Bulge')";
I would suggest using mysql_real_escape_string to correctly and safely quote strings. You might also like to have a look at using prepared statements instead with PDO or mysqli.
They are escaping because of PHP, not MySQL. You must escape " characters in "-" string because " character can be interpreted as the end of the string.
Look at the code coloring in your answer. The first string is colored wrongly: the parts in " and " are colored like code, not string
It's PHP which return a parse error.
From the point of view of PHP, a string is a sequence of characters delimited by quotes. One at the beginning and one at the end.
When you want to put quotes inside the string, you need to escape them, so PHP knows the internal quotes are not the end of the string.
Unless you escape them, PHP will return a parse error because the thing you're assigning to $query is not a valid string (with a quote at each end, only)
Related
I have the following query in a php file which works fine:
$query = "SELECT `name` FROM users WHERE name='".mysqli_real_escape_string($link,$name)."'";
I got it in a tutorial so I'm trying to wrap my head around the syntax. Specifically this part:
'".mysqli_real_escape_string($link,$name)."'
If the function mysql_real_escape_string() returns a string, why are double quotes needed? Also, I understand in php the . means concatenation so is this code adding to the empty string""?
Please help, I'm really screwed up on this one.
The double quotes are needed because this is using string concatenation to compose a query. This is a really messy way to do this sort of thing as the mysqli driver has support for placeholders:
$query = "SELECT `name` FROM users WHERE name=?";
The ? represents where your data will go. You then use the bind_param method to add your $name value in there.
If you're disciplined about using placeholders you won't have to worry about quoting or proper escaping.
The single quotes identify strings in the SQL query that you are building.
Your query will result for example in:
SELECT `name` FROM users WHERE name='John';
(note the quotes surrounding John)
The backticks are used to scape objects names.
There are two types of quotes in most computer programs, ' and ". You use two of the same type to enclose a string, like 'abc' or "def". However, when you need quotes inside the other quotes, you can put '"'. The syntax does not respond to the quote of different type. The same principle applies in here.
In this case, the line of code can be represented as
`$query = "SELECT `name` FROM users WHERE name=''";`
but the single quotes needs content in them. That gets added by the concatenation.
There is no empty strings in this code. The last "'" is just closing the single quoted string that was opened in name='". In mysql queries, strings must be enclosed in quotes and the here the function returns string which is enclosed in single quotes. This can be clarified like this:
$name = mysqli_real_escape_string($link,$name);
$query = "SELECT `name` FROM users WHERE name='".$name."'";
Suppose if the variable $name = 'Joffery'
Then the $query variable will be printed like this
SELECT `name` FROM users WHERE name='Joffery'
$data = "INSERT into detail(id,event) VALUES (1,"quest '15")";
Im having trouble with the single quote '15.i tried to use \'15 but doesnt seem to work.
try this:
$data = "INSERT into detail(id,event) VALUES (1,\"quest '15'\")";
Try this:
$data = "INSERT into detail(id,event) VALUES (1,'quest \'15')";
The problem isn't the single quote; the problem is the use of double quotes within a string literal that is enclosed in double quotes. Your double quoted string literal is actually being ended right before quest.
One alternative is to use single quotes for string literals within SQL text. Within a string literal, you'll need to "escape" the single quote, and one way to do that is by preceding a single quote by another single quote.
For example:
$data = "INSERT into detail(id,event) VALUES (1,'quest ''15')";
^ ^^ ^
If you do that, the value for the event column will be seen as quest '15
I strongly suggest using prepared statements, but in lieu of that, you can use mysqli_real_escape_string.
$data "INSERT INTO detail (id, event) VALUES (1, '".mysqli_real_escape_string("quest '15")."')";
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Correct way to escape input data before passing to ODBC
the error I am getting from querying a ODBC query is this:
(pos: 72 '...M = 'Owen O'^Donavon' AND...') - syntax error
and when I try to escape it:
(pos: 73 '... = 'Owen O\'^Donavon' AND...') - syntax error
the ^ means that is where it is breaking
I have tried the following:
NAM = '".$var."'
And also this:
NAM = '".mysql_escape_string($var)."'
then I got desperate
NAM = \"".$var."\"
Where $var is any name that contains a ' in it.
if you need the whole query:
UPDATE TABLE SET COLUMN1 = 'ERR' WHERE COLUMN_NAM = '".mysql_escape_string($var)."' AND COLUMN7 = 0");
does anybody know how I can get the quote properly escaped?
To include a single quote within a MySQL string literal (which is delimited by single quotes), use two single quote characters. e.g.
'I don''t like it'
Effectively, When MySQL parses that, it will see the two single quote characters, and will interpret that as one single quote within a literal, rather than seeing the "end" of the string literal.
But (as you are finding out) when you have only one single quote in there, the MySQL parser has a hissy fit over it. Consider this example:
'I don't like it'
What the MySQL parser sees there is a string literal, five characters in length, containing 'I don'. Then MySQL sees that literal as being followed by some more tokens that need to be parsed: t like it. The parser does NOT see that as part of a string literal. That previous single quote marked the end of the string literal.
So now, the MySQL parser can't make heads or tails of what t like it is supposed to be. It sees the single quote following these tokens as the beginning of another string literal. (So, you could be very clever about what appears there, and manage to get something that MySQL does understand... and that would probably be even worse.)
(NOTE: this issue isn't specific to ODBC; this affects clients that make use of string literals in MySQL query text.)
One way to avoid this type of problem is to use bind variables in your query text, vs. string literals. (But with MySQL, what's happening anyway, is that escaping, what gets sent to the MySQL server (behind the scenes, so to speak) is a string literal.
Sometimes we DO need to include string literals in our query text, and we shouldn't be required to use bind variables as a workaround. So it's good to know how to "escape" a single quote within a string literal which is enclosed in single quotes.
I was reading Does $_SESSION['username'] need to be escaped before getting into an SQL query? and it said "You need to escape every string you pass to the sql query, regardless of its origin". Now I know something like this is really basic. A Google search turned up over 20, 000 results. Stackoverflow alone had 20 pages of results but no one actually explains what escaping a string is or how to do it. It is just assumed. Can you help me? I want to learn because as always I am making a web app in PHP.
I have looked at:
Inserting Escape Characters, What are all the escape characters in Java?,
Cant escape a string with addcslashes(),
Escape character,
what does mysql_real_escape_string() really do?,
How can i escape double quotes from a string in php?,
MySQL_real_escape_string not adding slashes?,
remove escape sequences from string in php I could go on but I am sure you get the point. This is not laziness.
Escaping a string means to reduce ambiguity in quotes (and other characters) used in that string. For instance, when you're defining a string, you typically surround it in either double quotes or single quotes:
"Hello World."
But what if my string had double quotes within it?
"Hello "World.""
Now I have ambiguity - the interpreter doesn't know where my string ends. If I want to keep my double quotes, I have a couple options. I could use single quotes around my string:
'Hello "World."'
Or I can escape my quotes:
"Hello \"World.\""
Any quote that is preceded by a slash is escaped, and understood to be part of the value of the string.
When it comes to queries, MySQL has certain keywords it watches for that we cannot use in our queries without causing some confusion. Suppose we had a table of values where a column was named "Select", and we wanted to select that:
SELECT select FROM myTable
We've now introduced some ambiguity into our query. Within our query, we can reduce that ambiguity by using back-ticks:
SELECT `select` FROM myTable
This removes the confusion we've introduced by using poor judgment in selecting field names.
A lot of this can be handled for you by simply passing your values through mysql_real_escape_string(). In the example below you can see that we're passing user-submitted data through this function to ensure it won't cause any problems for our query:
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
Other methods exist for escaping strings, such as add_slashes, addcslashes, quotemeta, and more, though you'll find that when the goal is to run a safe query, by and large developers prefer mysql_real_escape_string or pg_escape_string (in the context of PostgreSQL.
Some characters have special meaning to the SQL database you are using. When these characters are being used in a query they can cause unexpected and/or unintended behavior including allowing an attacker to compromise your database. To prevent these characters from affecting a query in this way they need to be escaped, or to say it a different way, the database needs to be told to not treat them as special characters in this query.
In the case of mysql_real_escape_string() it escapes \x00, \n, \r,\, ', " and \x1a as these, when not escaped, can cause the previously mentioned problems which includes SQL injections with a MySQL database.
For simplicity, you could basically imagine the backslash "\" to be a command to the interpreter during runtime.
For e.g. while interpreting this statement:
$txt = "Hello world!";
during the lexical analysis phase ( or when splitting up the statement into individual tokens) these would be the tokens identified
$, txt, =, ", Hello world!, ", and ;
However the backslash within the string will cause an extra set of tokens and is interpreted as a command to do something with the character that immediately follows it :
for e.g.
$txt = "this \" is escaped";
results in the following tokens:
$, txt, =, ", this, \, ", is escaped, ", and ;
the interpreter already knows (or has preset routes it can take) what to do based on the character that succeeds the \ token. So in the case of " it proceeds to treat it as a character and not as the end-of-string command.
Can you tell me what is the different using (')single quotes inside (")quotes and (")quotes inside (')single quotes? and at concat, what is the meaning of this '".$bla."' I still can not distinguish them.
In SQL, anything with single quotes is considered a text based data type.
SQL uses double quotes for escaping keywords and non-ASCII characters.
This:
'". $bla ."'
..is PHP syntax. $bla is a PHP variable, the period is a string concatenation character (which is why there's one on both sides). So in this example, the content of the $bla variable is being concatenated into a string, where it will be surrounded by single quotes.
The main difference is the anything in a double quote is evaluated and anything in a single quote is not. There has been some discussion that it is better to use single quotes than double quotes so that PHP does not need to evaluate every aspect of the line to determine if it is a variable or not:
$good = 'really good';
echo "this is not $good"; //bad
echo 'this is' . $good; //good
It just keeps thing running faster and keeps the code looking cleaner.