Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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=''"...

like image 300
qwerty Avatar asked Dec 18 '25 18:12

qwerty


2 Answers

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().

like image 176
Donnie Avatar answered Dec 20 '25 12:12

Donnie


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.

like image 33
Felix Kling Avatar answered Dec 20 '25 10:12

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!