0

I want to query data in mysql like:

$cid=$_POST["cid"];
$room_id=$_POST["room_id"];
$time=$_POST["time"];

$reuslt=$this->db-query("SELECT * FROM mytable WHERE if($cid is not null){then check cid=$cid} else{don't check} AND if($room_id is not null){then check room_id=$room_id} else{don't check} AND if($time is not null){then check time=$time} else{don't check}");

How could I writ the correct sql to query data?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
TimLee
  • 183
  • 1
  • 2
  • 11

5 Answers5

1

So if you wanted to use an SQL if|else statement, look at something like Using an IF Statement in a MySQL SELECT query, or If else on WHERE clause.

Some other sql answers here look interesting too. However i would caution against overcomplicating.

For this OP its easier to prepare statement you send to DB, rather than overthink it and risk performance drop if massive dataset and poor indexes.

So, if this is more relevant as a php if|else, and you want to keep it as a single line (as opposed to concatenating a string over multiple statements), i would recommend ternary syntax

https://davidwalsh.name/php-shorthand-if-else-ternary-operators

For example, something like this should work:

$reuslt= $this->db-query("SELECT * FROM mytable WHERE TRUE " 
   . ( ($cid is not null) ? " AND cid='".$cid."'" : "" ) 
   . ( ($room_id != null) ? " AND room_id='".$room_id."'" : "" ) 
   . ( ($time != null) ? " AND  time='" . $time . "'" : "" );

The WHERE TRUE is just to make easier to print, though it really would be easier to just create a $sql string variable and prepare the statement over seperate if() statements.

Though i would also stress the need for escaping these values, as you should with all user input.

http://php.net/manual/en/mysqli.real-escape-string.php

Community
  • 1
  • 1
Daniel Brose
  • 1,394
  • 10
  • 24
  • btw - i kept mine simple php, even included his typos, but its obvious codeigniter and as i mention seperate lines also easier, so something like @yogendrayaduvanshi might be more perfered - mine is really just a starting point to show you how ternary can be used with just a little trick (where true). Some of the other sql 'case; and 'if' answers are also interesting, but for the use case of this OP just prepare statement before sending to DB, no need for extra complications or possible performance drop if massive dataset and poor indexes. – Daniel Brose Dec 17 '15 at 00:10
1

You can use 1=1 as a placeholder in an IF function in a WHERE clause:

$query = "SELECT * FROM mytable
    WHERE IF('$cid' != '', cid='$cid', 1=1)
    AND IF('$room_id' != '', room_id='$room_id', 1=1)
    AND IF('$time' != '', time='$time', 1=1)"
$result=$this->db->query($query);

I don't know how your framework handles it, but this code is seriously vulnerable to SQL injection and you should be using prepared queries with parameterization.

miken32
  • 42,008
  • 16
  • 111
  • 154
0

SQL Statement below would perform action you are going to make:

SELECT * FROM mytable WHERE (('$cid' is not null) AND (cid='$cid')) 
                      AND (('$room_id' is not null)AND(room_id='$room_id'))
                      AND (('$time' is not null) AND (time='$time'))
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
  • 1
    1) You need single quotes around `'$cid'` and such others, otherwise it will be considered as a fieldname 2) Probably the value coming from the inputs should not be `null` it can be `''` instead, and in that case, your condition will fail. – Tᴀʀᴇǫ Mᴀʜᴍᴏᴏᴅ Dec 15 '15 at 05:04
  • would it perform that action??? Im reading it as all parameters have to not be null, else a condition would fail and no results returned. Compare to mine, or others like @Praveen, where the conditions check for null before checking equality, and wont break if ANY is null. The OP states that for all values, 'only' if they are not null should they be checked, where yours would fail if any were null. – Daniel Brose Dec 17 '15 at 00:06
0

You can do this by case statement:

SELECT * 
FROM mytable 
WHERE 
    (cid = case when $cid is not null then $cid else cid end) AND 
    (room_id = case when $room_id is not null then $room_id else room_id end) AND 
    (time = case when $time is not null then $time else time end)
Praveen
  • 8,945
  • 4
  • 31
  • 49
0

This is how i do in my case and its working ..() In model

public function get($table,$column='*',$where='',$start='',$limit='',$seach_field='', $seach_keyword='', $seach_type='',$orderby='',$order_type='DESC')
    {
        $this->db->select($column); 
        $this->db->from($table);
        if($where !='')
        {
            $this->db->where($where);   
        }
        if($seach_field !='' && $seach_keyword !='' && $seach_type!='')
        {
            $this -> db -> like($seach_field, $seach_keyword, $seach_type);
        }
        if($orderby!='')
        {
            $this->db->order_by($orderby,$order_type);
        }
        if($limit!='')
        {
            $this->db->limit($limit, $start);
        }
        $que = $this->db->get();

        return $que->result_array();        
    }
yogendrayaduvanshi
  • 209
  • 1
  • 2
  • 14