سؤال

An input and script in index.php

<input type="text" class="filter" id="frClientName" name="cl_name">

<script>
    $(".filter").on('change keydown keyup', function(){
        var clname;
        clname = document.getElementById("frClientName").value;
        $("#spravaContent").load("php/search_results/sprava.php?cl_name=" + clname;
    });
</script>

php/search_results/sprava.php

$clname = '';
if ( isset ( $_GET['cl_name'] ) ) {
    $clname = $_GET['cl_name'];
}

$sql = ("
    SELECT * FROM `db`.`table`
    WHERE cl_full_name LIKE  '%".$_GET['cl_name']."%'
");

How can I use WHERE clause right and only if variable isn't empty? Thank you for some direction.

EDIT:

$sql = ("
    SELECT * FROM `db`.`table`
    ORDER BY {$oby} {$ohow}
    WHERE cl_full_name LIKE '%".$_GET['cl_name']."%'
    OR '' = '".$_GET['cl_name']."'
    LIMIT $start_sprava,$per_page_sprava
");
هل كانت مفيدة؟

المحلول

It's a bit hacky, but I've handled situations like this with a CASE statement. You evaluate your argument and if it doesn't meet the condition you require, you use an obviously true statement like 1=1 which has the net effect of keeping that part of the WHERE clause from participating in filtering the result set.

SELECT * 
  FROM `db`.`table`
 WHERE CASE WHEN TRIM('".$_GET['cl_name']."') IS NOT NULL THEN cl_full_name LIKE  '%".$_GET['cl_name']."%'
            ELSE 1=1
       END
 ORDER BY {$oby} {$ohow}
 LIMIT {$start_sprava}, {$per_page_sprava}
;

Don't forget to police your inputs so you don't wind up with a Little Bobby Tables problem. Also, the ORDER BY and LIMIT clauses generally come after the WHERE clause.

نصائح أخرى

Make the where clause work whether set or not.

Assuming your app language returns the text "null" if variable is not set:

"SELECT * FROM `db`.`table`
WHERE cl_full_name LIKE '%".$_GET['cl_name']."%'
OR 'null' = '".$_GET['cl_name']."'"
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top