如何将此mySql查询转换为PDO格式...?

时间:2014-07-16 10:30:26

标签: php mysql pdo

我应该如何为这种类型的查询编写PDO Prepare和bindValue / param语句,其中我检查该值是否为null然后只将其添加到查询字符串 ..... < / p>

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

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

1 个答案:

答案 0 :(得分:1)

快速回答,未经测试:

<?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);

每次查询获得更多过滤器时,只需按下param数组,使用名称应该更容易,我不确定array_push是否会保留订单,所以..