当 bindValue 为空时,我无法执行动态构建的查询
- 如果定义了 bindValue 但未使用,则查询不返回任何结果。只要为所有搜索字段输入值,我的查询就可以工作。
- 我已经尝试过 bindValue 和 bindParam。
- 目的是仅查询在搜索表单上填写的字段。
- 我在本地 MySQL 日志中注意到,除非使用所有 bindValue 搜索词,否则该语句将正确准备但不会执行。
这是 mysql.log(填写了所有 3 个字段):
142 Connect root@localhost on drawings03
142 Prepare SELECT * FROM draw WHERE (`LocationNumber` = ? && `DrawingNumber` = ? && `DrawingDate` >= ? )
142 Execute SELECT * FROM draw WHERE (`LocationNumber` = '525' && `DrawingNumber` = '101' && `DrawingDate` >= '1950' )
142 Close stmt
142 Quit
这是一段php:
<?php
//grabs variables from a search form
$searchTerms['locnum'] = $_GET['locnum'];
$searchTerms['drawnum'] = $_GET['drawnum'];
$searchTerms['projtitle'] = $_GET['projtitle'];
$searchTerms['shttitle'] = $_GET['shttitle'];
$searchTerms['shtnum'] = $_GET['shtnum'];
$searchTerms['discp'] = $_GET['discp'];
$searchTerms['drawdate'] = $_GET['drawdate'];
//Loops through the array
foreach ($searchTerms as $field => $value) {
if ($value != null && $value != '' && $value != ' ' ) {
// Based on the key name in the array, decide which
// SQL statement to add to the array to be constructed
switch ($field) {
case 'locnum':
$where[] = "`LocationNumber` = :locnum ";
break;
case 'drawnum':
$where[] = "`DrawingNumber` = :drawnum ";
break;
case 'drawdate':
$where[] = "`DrawingDate` >= :drawdate ";
break;
}
}
}
// Combine WHERE statements into one with && separating each one
$whereSQL = implode(' && ', $where);
$stmt = $db->prepare("SELECT * FROM draw WHERE (".$whereSQL.")");
$stmt->bindValue(':locnum', $locnum, PDO::PARAM_INT);
$stmt->bindValue(':drawnum', $drawnum, PDO::PARAM_INT);
$stmt->bindValue(':drawdate', $drawdate, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$row_count = $stmt->rowCount();
echo "<div class='span12'><b>".$row_count." results"."</b><br>Click <b>to sort</b>. Right-click link and save-as <b>to save a PDF</b>.</div>";
foreach ($rows as $value) {
echo $value['LocationNumber']." - ".$value['DrawingNumber']." - ".substr($value['DrawingDate'],0,4)."<br>";
}
?>