Having trouble with a mysqli query - specifically the WHERE stoname= clause.
This doesn't work:
$result = #mysqli_query($dbc, "SELECT * FROM thedb WHERE coname='{$_SESSION['user']}' AND stoname='{$_SESSION['store']}' ");
If I echo $_SESSION['store'] then it prints as o\'store which matches what's the in the database. Yet this doesn't work.
However, if I echo mysqli_real_escape_string($dbc,($_SESSION['store'])) then it prints o\\\'store which is NOT what's in the database. Yet it works.
$result = #mysqli_query($dbc, "SELECT * FROM thedb WHERE user='{$_SESSION['user']}' AND stoname='".mysqli_real_escape_string($dbc,($_SESSION['store']))."' ");
I accept that I have working code, but I'm confused as to why this the case. Can anyone explain what I've done / am doing wrong? Thanks
If your table literally contains o\'store then mysqli_real_escape_string() has done its job correctly. The function's purpose is to escape a string for safe inclusion inside a SQL statement, not to be an exact literal match for what is actually already in your table.
The table value contains literally \'. When you use that value directly in the SQL statement, the backslash is misinterpreted as an escape character to the ' rather than as a literal \ as appears in your table. So the query produces no results because the executed SQL statement is:
# MySQL sees only an escaped ' and no \
SELECT * FROM thedb WHERE coname='something' AND stoname='o\'store'
...meaning the value of stoname actually compared is just o'store without \, because \ has been discarded by MySQL as an escape character.
So mysqli_real_escape_string() produces a value with two changes.
First, the literal ' in your original string is backslashed escaped as \' for use in the SQL.
Then, the literal \ already in your string is itself backslash-escaped so that it can be understood as a literal characer by MySQL rather than an escape character. That results in \\. Combined with the escaped \', you now have \\\'.
MySQL receives that string \\\' and is able to correctly interpret it as one literal \ followed by one literal ' after discarding the extra \ escape character before each. The condition matches the column's actual value and your query is successful.
# MySQL sees an escaped \ followed by an escaped '
SELECT * FROM thedb WHERE coname='something' AND stoname='o\\\'store'
About storage...
We don't know much about how your table originally received its value, but I have a hunch it was stored in an escaped form. If the string o\'store was originally o'store without the \, it suggests that an escaped value was inserted in the table. That is not usually done, and is undesirable. Correct use of mysqli_real_escape_string() at the time of data insertion should store the original string rather than an escaped string. Escaping is only done when constructing SQL statements.
Related
I'm running this exact query from PHP:
UPDATE commentedText SET title='ยง2.', content='<div class=\"pageParagraph\"><p>Test</p>\n</div>', last_changed='1430422172', image_banner_url='', active='', comments='[{"from":"0","to":"0","id":"1","CommentedText":"","comment":"New test with \"test\" :d"}]' WHERE id='5541d52beb2ea' AND appId='MyAppID' LIMIT 1
However when I read the row that was updated (either via PHP or MySQL Workbench), the slashes are gone. See for example
<div class=\"pageParagraph\"[..]
which is saved to the table as
<div class="pageParagraph"[..]
How come the slashes disappear?
They are disappearing before they even get to MySQL -- PHP is seeing the backslash as an escape for the double quote.
"\""
creates a string "
To keep the backslash use
"\\\""
The first escapes the second, and the third escapes the quote.
Mysql also uses backslash escapes for strings. So to use it in a query, you need to have it escaped yet again.
"\\\\\""
PHP's string will be \\"
Which in MySQL will create a string \"
Use proper escaping when dealing with queries. Applying things like addslashes() are easily defeated.
Depending on your library, mysql_real_escape_string(), mysqli_real_escape_string(), or best yet, prepared statements.
These methods of escaping will not modify the original data, so you don't have to worry about removing the escaping characters on render.
I'm using PHP and Postgresql 9.0. I wish to insert a string eg.
"TiMxji+bhCJlk9OGcYosmBpEK8K+Li1Ygut9MJWFtpT8t0MlbGgMWJ7\/SHj8PjSWXoeGRmjjAqBTPQMe"
into a column using a prepared statement. The string generated is part of an authentication system and therefore must be entered exactly. My problem is that the backslashes are interpreted as escape characters rather than literal characters. Normally I believe I would just use the E operator to denote a string literal but this just throws up errors. Is there a way I can tell Postgres that this is a string literal while using a prepared statement?
Below is a simple example statement, where $1 is the string I wish to denote as a string literal.
pg_prepare($p->db,'setToken','UPDATE users SET token=$1 WHERE email=$2');
Thanks for your help,
Mark
$1 is the string I wish to denote as a string literal.
There's a contradiction in terms here, because writing a string as a literal is the opposite of feeding it via a parameter through the $1 placeholder.
If using a parameter, the code would be:
$result=pg_prepare($p->db, 'setToken','UPDATE users SET token=$1 WHERE email=$2');
// error checking on $result skipped
$result=pg_execute($p->db, 'setToken', array($token, $email));
If using $token and $email as string literals instead, the code could look like this:
$query = sprintf("UPDATE users SET token='%s' WHERE email='%s'",
pg_escape_string($p->db, $token),
pg_escape_string($p->db, $email));
$result=pg_prepare($p->db, 'setToken', $query);
// error checking on $result skipped
$result=pg_execute($p->db, 'setToken', array());
Both methods work, but method #1 is generally considered more foolproof and efficient.
Note about the backslash character: it is not true in general that \ must be escaped. In standard SQL, backslash is a normal character that must not be escaped. For compatibility reasons, PostgreSQL has a parameter standard_conforming_strings that when ON, tells that \ is normal, and when OFF tells it's an escape character.
The default value of this parameter is OFF up to 9.0 and ON starting with 9.1.
pg_escape_string knows about this setting and will take it into account automatically (unless you use an antiquated version of the postgresql client library).
And since you mentioned the E'...' prefix notation, when using it the \ is always an escape character in the string that follows, regardless of the standard_conforming_strings setting. General you don't want to stuff literals from php variables into E'...' postgresql constructs, it's unnecessarily hard because of the multiple levels of quoting involved.
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 have several post variables that I run through the following:
$input_name = mysqli_real_escape_string($dbc, trim($_POST['input_name']));
I have run several tests where I echo $input_name and other like variables before the insert query executes. The echo indicates that they are indeed getting escaped as they should.
However, when I login to phpmyadmin to look at my entries in the DB, I see that characters that should be escaped are not. Do I have a problem here? Is something happening between my variable declaration and the query that I am not aware of?
Are there php or server settings that could be influencing this?
note: I realize PDO is the way to go, I am just not there at this particular moment.
The echo indicates that they are indeed getting escaped as they should.
This indicates that your characters are escaped.
when I login to phpmyadmin to look at my entries in the DB, I see that characters that should be escaped are not
Now as you are escaping means that you want to those characters as it is rather than PHP or you database taking them internally as delimiters.
Like if you want ' in your input as it is, so your are escaping it.
So now when database(mysql) sees it that is is escaped so it won't considered it as a single quote that is used for string literals in MySQL.
If you don't escape it then MySQL will consider all the part between two ' as string literals.
So everything is fine, don't worry about it.
The *_real_escape_string functions in PHP are only there to prevent SQL injection therefor it will only change " to \" and ' to \' so that the following query:
SELECT * FROM users WHERE pass = '' OR '1'='1 --
Will become:
SELECT * FROM users WHERE pass = '\' OR \'1\'=\'1 --
So that the injected value won't work.
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.