Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When mysql WHERE clause is empty, return all rows

Tags:

php

mysql

where

$randomvariable=$_GET['randomvariable'];
$search="SELECT * from objects
          WHERE transactiontype='$randomvariable'
          order by id DESC";

Now if $randomvariable is empty (nothing), I would like it to return all rows. Currently if it's empty it returns nothing, because it basically searches for nothing from all of the rows.

like image 502
user1770565 Avatar asked Oct 24 '12 08:10

user1770565


1 Answers

$randomvariable = ESACPE_MYSQL_STRING($_GET['randomvariable']);
$search =
    "SELECT * FROM objects " .
    (empty($randomvariable) ? "" : "WHERE transactiontype='$randomvariable' ") .
    "ORDER BY id DESC";

Where ESCAPE_MYSQL_STRING is the relevant function for escaping strings for whatever MySQL driver you're using.

Another, more modular way:

$search = array(
    "select" => "SELECT * FROM objects",
    "where" => "WHERE transactiontype='$randomvariable'",
    "order" => "ORDER BY id DESC"
);

if (empty($randomvariable)) {
    unset($search["where"]);
}

$search = implode(' ', $search);

The nice thing about this is that you can add, remove or alter the query for any situation easily, having easy access to any part of the query.


You could also do this with CASE() in SQL, but it's somewhat cumbersome and you shouldn't expect good performance either:

SELECT * FROM objects
WHERE transactiontype LIKE
    CASE WHEN '$randomvariable' = '' THEN
        '%'
    ELSE
        '$randomvariable'
    END CASE
ORDER BY id DESC
like image 61
rid Avatar answered Oct 10 '22 20:10

rid