In a database, I have some text stored in a field call Description, the value of the string saved in my database is Me\You "R'S'" % and thats how it appears when querying the database command line.
Now, on a web page i have a function which searches this field as such:
WHERE Description LIKE '%$searchstring%'
So when $searchstring has been cleaned, if i was searching for Me\You, the backslash gets escape and my query reads:
WHERE Description LIKE '%Me\\You%'
However it doesn't return anything.
Strange part of this, is that when i search Me\\You or Me\\\You (So two or three backslashes, but no less or no more) it will return the result i expect with one backslash.
When querying for the result command-line, it does not return a result for:
WHERE Description LIKE '%Me\You%'
or when i use two or three backslashes.
However it will return the result if i use 4 - 7 backslashes, for example:
WHERE Description LIKE '%Me\\\\\\\You%'
will return the string which is Me\You "R'S'" %
Anyone have a reason to this happening? Thanks
Note
Because MySQL uses C escape syntax in strings (for example, “\n” to represent a newline character), you must double any “\” that you use in LIKE strings. For example, to search for “\n”, specify it as “\\n”. To search for “\”, specify it as “\\\\”; this is because the backslashes are stripped once by the parser and again when the pattern match is made, leaving a single backslash to be matched against.
Source: http://dev.mysql.com/doc/refman/5.1/en/string-comparison-functions.html#operator_like
Read this Need to select only data that contains backslashes in MySQL to see how to use double backslash escaping. You could also run MySQL in NO_BACKSLASH_ESCAPES mode (http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_no_backslash_escapes)
Although an old post, you can bypass this limitation using replace function to change backslash to another character: something like this in the WHERE clause. EXAMPLE:
WHERE replace('your field here', '\', '-') like "You-Me%"
Related
I have a MySQL database with a column containing part numbers. Some of the part numbers contain spaces:
3864205010 J
When I query the database or search for the part in phpMyAdmin no results are returned.
Yet when I delete the 2 spaces and then type them again, the search returns a result.
This query does not return a result:
SELECT *
FROM `parts`
WHERE `part_no` LIKE '3864205010 K'
This query returns the result:
SELECT *
FROM `parts`
WHERE `part_no` LIKE '3864205010 K'
They look the same but in the second query I have deleted the 2 spaces before "K" and typed the spaces again.
If you can use wildcard instead of spaces:
SELECT *
FROM `parts`
WHERE `part_no` LIKE '3864205010%K'
This is probably not a space but a HTAB (ascii code 9) or even a line feed/carriage return (10 and 13). Copy paste in a good text editor, you'll see what it really is.
Now, regarding to your wonder about why it doesn't work even if it does look like a space, this is because every single character we see is interpreted by the engine (notepad, phpmyadmin, firefox... any software with text rendering)
What actually happens is that when the engine finds an ascii code, it transforms it into a visible character. The CHAR(9) for example is often transformed into a 'big space' usually equal to 2 or 4 spaces. But phpmyadmin might just decide to not do it that way.
Other example is the line feed (CHAR(10)). In a text editor it would be the signal that the line ends, and (under unix systems mostly) a new line has to start. But you can copy this line feed into a database field, you're just not sure about how it is going to render.
Because they want you to see everything in the cell they may choose to render it as a space... but that's NOT a space if you look at the ascii code of it (and here there's no trick, all rendering engines will tell you the right ascii code).
This is important to always treat characters with their ascii codes.
there's an answer above that suggests using a wildcard instead of the spaces. That might match, or just might not. Let's say your string is '386420K5010', so it is not the one you're looking for, still the LIKE '3864205010%K' pattern would return it. The best is probably to use a regular expression or at least identify the fixed pattern of these strings.
yes as updated question if you wish to remove more space between which contents might be 3 or 4 space below query will use full to you
SELECT REPLACE( REPLACE( part_no, " ", " " ), " ", " " ) from parts.
let me know if it is work for you ?
SELECT *
FROM `parts`
WHERE REPLACE(REPLACE(`part_no`, CHAR(9), ''),' ','') LIKE REPLACE(REPLACE('3864205010 K', CHAR(9), ''),' ','')
This will probably work if part_no and/or search string has tabs and/or spaces.
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'm using codeigniter, and what I do is basically:
$val = $this->db->call_function('real_escape_string', $this->input->post('name'));
this is all I do on data before putting into database. And when someone enters value like O'hara, in database it will appear like O\'hara
So, I guess I can string slashes on output, but is this usual way of escaping and storing data in database?
SOLVED
Active Records escapes the query, so I do double escaping, with 'real_escape_string' function as well
So I guess I don't need to use real_escape_string at all, active records does this
The '\' is called an escape character and must be used so the next character after it (in your case ') won't interfere with the SQL statement. However, if you're using CI, it should take care of all of this for you. There's an 'HTML helper' that I believe you can use to format or take out the slashes on outputted text. Even then, but I could be wrong, when outputting values from a DB in CI, the slashes will automatically be stripped.
Escaping quotes and special characters is both regular practice and expected for record storage as it helps to ensure that your code can be accurately stored and extracted.
Escaping the strings for the SQL query is so that you can get the actual values into the database.
The value in the SQL query will look like O\'hara but the value that ends up in the database is O'hara.
So, you don't have to do anything at all when you display the value. Except escaping it for the environment where you display it of course. If it's displayed in a HTML document, you would HTML encode it. This will not change the apostrope ('), but it will change other characters, like < and >.
use directly
$val = real_escape_string($this->input->post('name'));
So i am trying to do a LIKE query and get some results but the text that i pass has some special characters that break the query.
if we assume that the text is something like this:
var test `select` `query`="$newval + "dsadsa$ ? "$test ?
and i also have exactly the same text inside a column as VARCHAR
and then executing the query
SELECT * FROM table WHERE column LIKE '%$text%'
says that there is no rows to return.
EDIT: when i post the data inside the database i simply use mysql real escape string and when i show the text where i click to search i put htmlentities on the text
then i substr it from 0 to 50 and do the search query
You can use mysql_real_escape_string() which will escape any special characters in your string.
Try to avoid writing variables directly into string, it may cause problems (+ it's really not nice):
mysql_query("SELECT * FROM table WHERE column LIKE '%" . $text . "%'");
Of course make sure that the $text variable is really correct (echo $text), characters escaping may cause problems too and of course there can be many other things causing problems (this depends on architecture of your application - where you work with $text).
I am trying to store regular expression search and substitution strings in a database. At runtime, I read the database, placing the strings into arrays, and then use the PHP preg_replace() method to update large strings written by users with fixes that my client wants.
Here is a sample string pair I am using:
Search string: /([^\r\n+])(\[url)/i
Substitute string: $1\n\n$2
If I place the string in code like this:
preg_replace("/([^\r\n]+)(\[url)/i", "$1\r\n\r\n$2", ProcessString);
Everything works beautifully. This finds instances of a bbCode tag "[url" that does not have a carriage-return/linefeed combination directly in front of it and places that in front of the "[url" tag.
However, when I run the code as I stated using strings from the database (MySql), the "\r\n\r\n" print literals instead of actually creating carriage-return line feeds. The strings are displayed in a "textarea" tag in HTML.
I have looked at the difference between single and quoted strings and my problem would seem to be this, I am assuming? Thinking that the problem is that the strings coming from the database or inserted into the array I'm looping through are created as single-quoted strings, I tried this:
preg_replace($findKey, "{$replaceValue}", ProcessString);
Where $replaceValue = the string '$1\r\n\r\n$2' (again, I am assuming that reading from the database and/or placing the value into an array (mysql_fetch_assoc($result)) is placing the string value into a single-quoted string and therefore the escaped characters are printing as literals instead of the characters the escaped characters actually represent. However, this did not work.
Here is the code I'm using to insert into the database:
INSERT INTO ISG_TCS_Replacements (FindPhrase, ReplacePhrase, ReplacementGroupID, Description, IsRegEx, IsActive, ProcessGroup, ProcessSequence)
VALUES ("/([^\\r\\n]+)(\\[url)/i","$1\\r\\n\\r\\n$2", 0, "Add a new line after [url] tags that are not on a new line currently.", 1, 1, 0, 1);
The fields are varchar(100).
The issue is that \r\n escapes only work in double quoted strings.
print "\r\n";
Whereas your database usage is likely akin to:
$replaceValue = '\r\n';
print "{$replaceValue}"; // uses the literal character string
You are inserting your replacement string with single quotes into the DB. Otherwise you would get the the actual linebreaks back. Mysql does escape them while inserting, but you always get the original string data back.
Reading from a MySQL TEXT/CHAR column is no different than reading from files really. Check your database with mysqladmin, if you see the literal \r\n then there is your problem.
(A literal '\r\n' btw works in the regex, but not in the replacement string.)
Something else. ([^\r\n+]) is probably meant to be ([^\r\n]+). The quantifier must be outside of the character class.