MySQL query: select all if REGEXP $var is empty? - php

$cities = "Amsterdam|Rotterdam|Den Haag"
$results = mysql_query("SELECT * FROM messages WHERE content REGEXP '$cities'");
The above code works great, but if $cities is empty, nothing is selected. I'd like to select all rows if $cities has no value. How can I achieve that? Thanks!

You will need to use a conditional in your php, which removes the where clause when your $cities variable is empty. Alternatively, you can use a regex that matches everything like /^/, but it's not particularly elegant.

you should check to see if the $cities is empty. If it is you can replace it with .* (match everything) or remove the from clause from the query (would increase performance)

$results = mysql_query("SELECT * FROM messages".
(empty($cities)? "":" WHERE content REGEXP '$cities'"));
Or probably
$results = mysql_query("SELECT * FROM messages WHERE '$cities' = '' OR content REGEXP '$cities'");

Related

PHP - MySQLi Replace with Regex / Regexp / Regular Expression

Sorry for that "Let me google that for you"-Question, but I can't find an answer.
I want to delete specfic elements from columns in my database. So I search with the following code for them: (it works fine)
$sql = "SELECT list_id, list_domains
FROM list
WHERE list_domains REGEXP '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#'";
$result = $db->prepare( $sql );
$result->execute();
$result->bind_result( $list_id, $list_domains );
$result->store_result();
Now I want to delete / replace the found elements inside these columns. So I use the following code:
$sql = "UPDATE list
SET list_domains = REPLACE(list_domains, '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#', '')
WHERE list_domains REGEXP '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#'";
$result = $db->prepare( $sql );
$result->execute();
$result->store_result();
Does not work. I also tried
REPLACE(list_domains, REGEXP '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#', '')
or
REGEXP_REPLACE(list_domains, '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#', '')
but these lines only produce errors.
How does it work to delete / replace specfic regular expressions with MySQLi?
Thanks for every suggestion!
REPLACE() doesn't allow regular expression searching.
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
If you want to manipulate strings with regex, SELECT the rows, do the manipulation in your own code, then issue an UPDATE statement to update the value, specifying the final value.

How to search a column for an exact string in SQL

My goal is to search column A for string B and if it is found, return which row it was found in, and if it wasn't found, I would need to know that as well in order to take a different course of action.
My current PHP code:
$string = "teststring";
$searchquery = "SELECT *
FROM AllStringsTable
WHERE `Column_A` LIKE '$string'"
$searchresult = mysql_query($searchquery) or die(mysql_error());
$row = mysql_fetch_row($searchresult);
echo "The returned row was: $row";
This just breaks and does nothing, so I think I'm way off here. Also, I have read that for exact string searching that doesn't require wildcard substrings, etc, LIKE is not needed. So I'm not sure what I would use instead...
You're almost there. You need the % wildcards:
// First, prevent sql injection with mysql_real_escape_string
$string = mysql_real_escape_string($string);
$searchquery = "SELECT * FROM AllStringsTable WHERE `Column_A` LIKE '%{$string}%'";
// ----------------------------------------------------------------^^^-------^^^
$searchresult = mysql_query($searchquery) or die(mysql_error());
if (mysql_num_rows($searchresult) == 0) {
echo "no rows found";
}
else {
// You need to loop over the result resource to get all the rows.
// Better to use mysql_fetch_array()
while ($row = mysql_fetch_array($searchresult)) {
$print_r $row;
}
If you want to do an exact match, use = instead of LIKE:
SELECT ... WHERE Column_A = '$string';
If you want to do a substring match (which I suspect is more what you want), use LIKE with the % wildcards:
SELECT ... WHERE Column_A = '%$string%';
The difference is that the first query requires that the entire Column_A matches exactly. The second query requires only that the exact word is found somewhere in the column.

How to select results from a MySQL DB using Strpos instead of a While statement?

I have been using the PHP function strpos to find results containing the characters of a string from a DB:
User Types: Hel
Results: Hello, Hell, Helli, Hella
I have it basically query the entire table:
$result = mysql_query("SELECT * FROM Events");
And then ran a while statement to see which of the results contain the characters of the input:
while($row = mysql_fetch_array($result))
{
$pos = strpos($row['Title'], $q);
if ($pos === false) {
} else {
echo $row['Title'];
}
}
And to find the number of results, I was using:
$n = $n++
Inside of the while statement.
I know you can use:
$num_rows = mysql_num_rows($result);
To find the number of results if you are only selecting those values from the database, but do I have to use this while statement to find the number of results that match the strpos function? Or can I put the strpos in to the Select From query?
Any help is greatly appreciated,
Taylor
This seems highly inefficient. Why wouldn't you simply let the database do the searching for you?
$result = mysql_query("SELECT * FROM Events WHERE Title LIKE '" . addslashes($q) . "%'");
Then just loop through the results.
You could update your SQL to something like
SELECT *
FROM Events
WHERE Title LIKE '{your_string}%'
Make sure to filter for sql injection though.
You can use the LIKE statement:
SELECT * FROM Events WHERE field1 LIKE '%something%'
Where the special % characters say "Anything of any length"; so we're searching for something (or nothing), then the string, then something (or nothing.) For example, searching for %f% will match foo, off, and affirmative.
Just as general advice, I recommend that you use php's MySQLi class; it's an improved version (hence the i), and provides prepared statements, so you won't have to worry too much about SQL injections.

Using PHP variable inside a query

I am using a query inside PHP as:
$query = 'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.$_GET['title'].'%" and text_7 like "%'.$_GET['author'].'%" limit 0,1';
Where I am trying to insert a PHP variable instead of 1 in the limit..
$query = 'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.$_GET['title'].'%" and text_7 like "%'.$_GET['author'].'%" limit 0,"'.$_GET['limit'].'"';
but it shows me an error. There are some errors in keeping $_GET['limit'].
Three things:
The way you're writing out those queries is a bit hard to read. Personally I prefer using a multi-line heredoc syntax (as per below), but this isn't strictly required;
Any user input should go through mysql_real_escape_string() to avoid SQL injection attacks. Note: "user input" includes anything that comes from the client including cookies, form fields (normal or hidden), query strings, etc.; and
You don't need to quote the second argument to LIMIT clause, which is probably the source of your problem, meaning put LIMIT 0,5 not LIMIT 0,"5".
So try:
$title = mysql_real_escape_string($_GET['title']);
$author = mysql_real_escape_string($_GET['author']);
$limit = (int)$_GET['limit'];
$query = <<<END
SELECT *
FROM #__chronoforms_UploadAuthor
WHERE text_6 LIKE "$title%"
AND text_7 LIKE "%$author%"
LIMIT 0,$limit
END;
Also, one commentor noted that % and _ should be escaped. That may or may not be true. Many applications allow the user to enter wildcards. If that's the case then you shouldn't escape them. If you must escape them then process them:
$title = like_escape($limit);
function like_escape($str) {
return preg_replace('!(?|\\)((?:\\)*)([%_])!', '$1\$2', $str);
}
That somewhat complicated regular expression is trying to stop someone putting in '\%' and getting '\%', which then escape the backslash but not the '%'.
The hash sign (#) starts a comment in SQL, which looks like your problem
Want bunch of awful answers!
a. To solve the limit problem:
$limit = intval($_GET['limit']);
and then
...LIMIT 0, $limit
in the query.
b. To sanitize $_GET['title'], as many mentioned:
$title = mysql_real_escape_string($_GET['title']);
So the final code must be
$limit=intval($_GET['limit']);
$title = mysql_real_escape_string($_GET['title']);
$author = mysql_real_escape_string($_GET['author']);
$query = "SELECT * from #__chronoforms_UploadAuthor
WHERE text_6 like '$title' and text_7 like '%$author%'
LIMIT 0, $limit";
You've enclosed the $_GET['limit'] in double-quotes, which is the source of the problem.
Try this:
$query = 'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.$_GET['title'].'%" and text_7 like "%'.$_GET['author'].'%" limit 0,'.$_GET['limit'];
Also as Cletus mentions in this answer, there are many, more serious problems you need to resolve.
Remove the double-quotes around $_GET['limit']. The two numbers that the LIMIT clause takes should not be quoted.
This should work:
$query = 'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.$_GET['title'].'%" and text_7 like "%'.$_GET['author'].'%" limit 0,'.$_GET['limit'];
But you really should filter incoming data...
$query = 'SELECT * from #__chronoforms_UploadAuthor where text_6 like "%'.mysql_real_escape_string($_GET['title']).'%" and text_7 like "%'.mysql_real_escape_string($_GET['author']).'%" limit 0,"'.intval($_GET['limit']).'"';

PHP mysql - ...AND column='anything'...?

Is there any way to check if a column is "anything"? The reason is that i have a searchfunction that get's an ID from the URL, and then it passes it through the sql algorithm and shows the result. But if that URL "function" (?) isn't filled in, it just searches for:
...AND column=''...
and that doesn't return any results at all. I've tried using a "%", but that doesn't do anything.
Any ideas?
Here's the query:
mysql_query("SELECT * FROM filer
WHERE real_name LIKE '%$searchString%'
AND public='1' AND ikon='$tab'
OR filinfo LIKE '%$searchString%'
AND public='1'
AND ikon='$tab'
ORDER BY rank DESC, kommentarer DESC");
The problem is "ikon=''"...
and ikon like '%' would check for the column containing "anything". Note that like can also be used for comparing to literal strings with no wildcards, so, if you change that portion of SQL to use like then you could pre-set the variable to '%' and be all set.
However, as someone else mentioned below, beware of SQL injection attacks. I always strongly suggest that people use mysqli and prepared queries instead of relying on mysql_real_escape_string().
You can dynamically create your query, e.g.:
$query = "SELECT * FROM table WHERE foo='bar'";
if(isset($_GET['id'])) {
$query .= " AND column='" . mysql_real_escape_string($_GET['id']) . "'";
}
Update: Updated code to be closer to the OP's question.
Try using this:
AND ('$tab' = '' OR ikon = '$tab')
If the empty string is given then the condition will always succeed.
Alternatively, from PHP you could build two different queries depending on whether $id is empty or not.
Run your query if search string is provided by wrapping it in if-else condition:
$id = (int) $_GET['id'];
if ($id)
{
// run query
}
else
{
// echo oops
}
There is noway to check if a column is "anything"
The way to include all values into query result is exclude this field from the query.
But you can always build a query dynamically.
Just a small example:
$w=array();
if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";
if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where='';
$query="select * from table $where";
For your query it's very easy:
$ikon="";
if ($id) $ikon = "AND ikon='$tab'";
mysql_query("SELECT * FROM filer
WHERE (real_name LIKE '%$searchString%'
OR filinfo LIKE '%$searchString%')
AND public='1'
$ikon
ORDER BY rank DESC, kommentarer DESC");
I hope you have all your strings already escaped
I take it that you are adding the values in from variables. The variable is coming and you need to do something with it - too late to hardcode a 'OR 1 = 1' section in there. You need to understand that LIKE isn't what it sounds like (partial matching only) - it does exact matches too. There is no need for 'field = anything' as:
{field LIKE '%'} will give you everything
{field LIKE 'specific_value'} will ONLY give you that value - it is not partial matching like it sounds like it would be.
Using 'specific_value%' or '%specific_value' will start doing partial matching. Therefore LIKE should do all you need for when you have a variable incoming that may be a '%' to get everything or a specific value that you want to match exactly. This is how search filtering behaviour would usually happen I expect.

Categories