adding a condition to a WHERE clause based on a passed variable value mysql -


i relative novice , use problem.

this used in search filter situation. users need search value , 1 or more other values passed search form.

$name = $_post['name']; $sdate = $_post['sdate']; $startdate = $_post['startdate']; $enddate = $_post['enddate']; $vehicle = $_post['vehicle']; $triptype = $_post['triptype'];  

if of these values '' not want them in query, if contain value want them in query.

select * form_data `resp_person` = '$name',   if $sdate != '' `sdate` = '$sdate',   if $startdate != '' `sdate` = *all values between $startdate , $enddate*,   if $triptype != '' `triptype` = '$vehicle',   if $vehicle != '' `vehicle` = '$vehicle', `sdate`   order `sdate` desc, `stime` desc") 

i know code wrong should give idea of trying accomplish. guidance appreciated.

a better way not use string concatenation build entire query, rather use sql library supports prepared statements, such pdo.

$pdo = new pdo('... connection string ...', username, password); $where = ''; $possible_values = array('name', 'sdate', 'startdate', 'enddate', 'vehicle', 'triptype' ); $params = array(); foreach($possible_values $val) {     if(isset($_post[$val]))     {         $params[] = $_post[$val];         if($where == '')         {             $where = "where $val = ?";         }         else         {             $where .= " , $val = ?";         }     } } $stmt = $pdo->prepare("select * form_data " . $where); $stmt->execute($params); 

Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -