Escaping meta characters in PHP - php

I was surprised to discover that the MySQL query
SELECT * WHERE name LIKE "%AFA_";
returns rows where name is SAFARI. To get it to match on the underscore, you have to do:
SELECT * WHERE name LIKE "%AFA\_";
Is there a PHP function that can do this transition or do I have to use str_replace?

PHP has no knowledge of MySQL LIKE wildcards, nor should it.
It does, however, have a way to escape things in strings if you want, and that is str_replace.
Replace instances of _ with \_, or whatever you like.
Ultimately this question has nothing to do with MySQL.

Related

Is it possible to use _ as an normal character in MySQL query while using LIKE keyword [duplicate]

This question already has answers here:
How to escape underscore in the string query in hibernate and SQL?
(2 answers)
Closed 1 year ago.
I have one MySQL query which is using LIKE for matching a string with one of my tables columns, and it's working fine in most of the scenarios.
select * from TableName where Column like "%STRING%"
But No I have one group of records that have "_0" in it. in this case, I get a get query something like this.
select * from TableName where Column like "%_0%"
in this case, MySQL is taking _ as a wildcard and skipping the first index from the string
Now my question is, is it possible to make this search work as it is, any way to tell MySQL it's not ( _ ) wildcard, So search for the string.
I will really appreciate your help.
Thanks in advance.
Query Result Image
You can use a backslash to escape it:
where Column like '%\_0%'
Or use your own escape character:
where Column like '%$_0%' escape '$';

PHP: Search and replace UNION with it's variations and then replace back

This is a question about string manipulation, not about database security. I am fully aware of PDO and prepared statements.
I want to prevent the word "UNION" from being inserted into my database. It's not the only one, there's a list: "EXECUTE", "DROP", etc. I'm using "UNION" as an example.
My plan is to use str_replace() on any given string (which includes full SQL statements, not just the values) and convert any occurrence of "UNION" into some other arbitary string and then insert the result into the database. E.g. "my union called a vote" would become "my #noinu# called a vote".
When the content is pulled from the database to be displayed on the front-end, any occurrences of "#noinu#" would be replaced with "union".
The words to be replaced are SQL keywords which work regardless of case so I have no case-matching on this.
The problem is that when someone enters, for example, "Union of unions" (capital U on the first word) the result that is eventually printed back out is "union of unions" with small letters.
If I try to account for uppercase, lowercase and proper case then I still miss instances like this, "uNiOn" which would still run in MySQL.
I figured some kind of regular expression would be part of the solution and then I draw a blank.
How can I identify case variations of a word (without manually defining all combinations), replace each variation with it's own custom replacement and then replace them back afterwards?

Trouble with LIKE MySQL query

I have the following MySQL query that I execute from a .php page
SELECT * FROM servers WHERE name LIKE '%$value%'
which, when executed, selects 0 rows (However, the query runs successfully, so I can't use mysql_error() to debug). When I run the query in PHPMyAdmin it selects the appropriate rows. Other queries such as
SELECT * FROM servers
work fine. I can put my code up here if it will help.
Edit: Here's something offering an improvement based on Marek's answer below. Please see the comments regarding the practice of putting variables directly into queries and consider using prepared statements. Anyway, here it goes.
PHP substitutes variables inside doubly-quoted strings, but not inside singly-quoted strings.
One quote character is just treated as an ordinary character within a string delimited by the other.
Putting that together, you can write:
$q = "SELECT * FROM servers WHERE name LIKE '%$value%'"; //Fine
You cannot write:
$p = 'SELECT * FROM servers WHERE name LIKE "%$value%"'; //Broken!
$q works because it's a doubly-quoted string, and the apostrophes are just ordinary characters. $p does not work because it's a singly-quoted string.
As pointed out by GoodFather below, you can also say ${value} to avoid ambiguities with the ambient string, e.g. $r = "ABC${value}DEF";.
You really need to look at doing this query more safely. This will help with your issue as well. As it stands, you are vulnerable to SQL injection. Look at the examples from the PHP manual for how to do it right:
http://php.net/manual/en/function.mysql-query.php
EDIT: From your comments you mentioned that you are already taking care of the string properly, which is great. The code below should fix your problem.
For example, you could rewrite your query statement (in PHP) like so:
$query = sprintf("SELECT * FROM servers WHERE name LIKE '%". mysql_real_escape_string($value) . "%'");
That will clean up your code and it will also handle the issue with your LIKE statement not working properly.
Here is another good article on the subject:
http://joshhighland.com/blog/2008/07/06/php-sprintf-sql-like/
Are you expecting a case-sensitive or case-insensitive query? I'm betting case-insensitive since you're expecting results but not seeing them. Take a look at your database's default collation or the table's specific collation and make sure it ends in _ci, whatever it is.

MySQL: escape space from query

Is there a way using MySQL, to query a value containing a space, but as some sort of escape character? It's for an instant search engine I'm building (I'm trying to incorporate special search strings such as quotes to search for exact string).
cheers
select * from sometable where somefield like '%oh no%';
Full-text indexes are what you should use. They handle all sorts of key words/characters (such as quoting a string to get exact match, -someword for saying someword can't be in the result and +someword for saying someword has to be in the result) without having to do anything special in your code (other than changing your query a little). The database will do the search for you and return the most relevant results at the top of the query. It is really quite easy to get going too.
Mysql Manual
Using full-text searching (implementation help)

match a word from a sentence in MYSQL using regex

How can I match a word in a sentence from a column using regex? I tried:
"select * from table where column regex '/\b".$text."\b/i'"
but that didn't work.
Try this:
"SELECT * FROM table WHERE column REGEXP '[[:<:]]" . $text . "[[:>:]]'"
You should make sure that any characters that could be interpreted as special characters in $text are properly escaped. You should also ensure that you do not get an SQL injection.
MySQL is particularly bad about stuff like this. I'd recommend using MATCH AGAINST syntax http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html or using something like SOLR if you're going to be doing this in volume.
I think you want the LIKE clause!
SELECT * FROM table WHERE column LIKE '%value%'
Also please read UltimateBrent's answer as full text search is a very good point.

Categories