简体   繁体   中英

How to convert this mySql query to PDO format…?

How should i write my PDO Prepare and bindValue/param statement for this type of query where i check whether the value is not null then only add it to the query string .....

$query = "SELECT * FROM cabs WHERE DATE='$date' ";
if ($mode!=='' || $mode!=="")
  $query .="AND MODE='$mode' ";

if ($tfno!=='')
  $query .="AND TFNO='$tfno' ";
  $query .="ORDER BY TIME";

Quick answer, without testing:

<?php
$params = array(':date' => $date);
$query = "SELECT * FROM cabs WHERE DATE=':date' ";
if ($mode!=='' || $mode!=="") {
  $query .="AND MODE=':mode' ";
  $params[':mode'] = $mode;
}

if ($tfno!=='') {
  $query .="AND TFNO=':tfno' ";
  $params[':tfno'] = $tfno;
}
$query .="ORDER BY TIME";

$req = $dbh->prepare($query);
$req->execute($params);

Just push in the param array each time your query gets more filters, and using a name should be easier, I'm not sure that array_push would preserve the order, so ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM