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'
Related
SQL LIKE is not working when string contains single quote ',
Below is my php code
$keysearch = "St.Joseph's"; // Searching keyword containing single quotes
$sql =mysqli_query("select id,name from tbl where name LIKE '%$keysearch%'");
It returns no result,
How can I search a string contain single quotes?
Is there any effective operator except 'LIKE' for comparing single quotes value in DB?
Use addslashes() function of PHP as below,
$sql =mysqli_query($con,"select id,name from tbl where name LIKE '%".addslashes($keysearch)."%'");
MySql Code
SELECT replace(replace(v.image_path,"\\","/"),"%s","_120") as image_path
FROM `artistkr_fox`.`phpfox_video` v;
My phpfox service file query string
$aVideos = $this->database()->select("REPLACE(REPLACE(v.image_path,'\','/'),'%s','_120') as image_path" . Phpfox::getUserField())
->from($this->_sTable, 'v')
->execute('getSlaveRows');
This query can't return any value
error throw in this code "REPLACE(v.image_path,'\','/')"
You need to make sure you are not mixing the quotes of the PHP string and your SQL query.
You can do this by either by escaping them using backslashes in front of your quote (\')
$query = 'SELECT replace(replace(v.image_path,"\\","/"),\'%s\',\'_120\') as image_path FROM artistkr_fox.phpfox_video v';
or by using double quotes (") for the PHP string and single quotes (') for your SQL query:
$query = "SELECT replace(replace(v.image_path,'\\\\','/'),'%s','_120') as image_path FROM artistkr_fox.phpfox_video v";
(Note when using double quotes for the PHP string, you need to escape the backslashes in y our SQL query)
Which one you choose depends on your preference and the situation (e.g. complexity of the query).
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.
$url = "What's up with "You doing this"";
$q = sprintf ("update user set url='%s'",$url);
pg_query ($db_conn, $q)
I want to insert everything into the database exactly as the user wants. I don't want to escape anything. The above would fail for me because of the quotes. I know single quotes have to go around the postgresql string (url='%s'). Since there are double quotes in my url string the query will not update because of it. I'm sure I could do a string replace for all double quotes and make them single quotes but what if the user really wants double quotes. And I cannot use string replace to put a backslash because according to the postgresql docs the slash will be deprecated soon (http://www.postgresql.org/docs/8.1/interactive/sql-syntax.html) plus that goes against inserting only what the user inputted.
What do people suggest I do?
Use pg_escape_string to escape quote characters in your string.
Use parametrized queries:
pg_query_params
(
$db_conn,
"UPDATE user SET url = $1",
array('What's up with "You doing this"')
);
escape your double quotes in the text like this
$url = "What\'s up with \"You doing this\"";
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)