PHP PDO动态查询构建

时间:2015-04-30 05:53:13

标签: php mysql pdo

$arr = array();
$from_date = '2015-01-01';
$to_date = '2015-01-31';
$order_no = '25215';
$sql = "SELECT * FROM test";
if(!empty($from_date)&&!empty($to_date))
{
    $sql.=" WHERE txn_date BETWEEN :from_date AND :to_date";
    $arr[] = ":from_date => $from_date";
    $arr[] = ":to_date => $to_date";
    $condition=true;
}
if(!empty($order_no))
{
    if($condition)
    {
       $sql.=" AND ref_number = :order_no";
       $arr[] = ":order_no => $order_no";
    }
    else
    {
       $sql.=" WHERE ref_number = :order_no";
       $arr[] = ":order_no => $order_no";
       $condition=true;
    }
}
$stmt = $db->prepare($sql);
$stmt->execute($arr);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

执行此查询时会显示类似

的警告
  

警告:PDOStatement :: execute():SQLSTATE [HY093]:参数号无效:参数未定义

它出了什么问题?

2 个答案:

答案 0 :(得分:2)

在变量$ arr中,您应该替换所有关联索引

$arr[':from_date'] = $from_date;
$arr[':to_date'] = $to_date;
$arr[':order_no'] = $order_no;

最好在外部块中移动公共代码而不是if / else梯形图

if(!empty($order_no))
{
    $arr[':order_no'] = $order_no;
    if($condition)
    {
       $sql.=" AND ref_number = :order_no";
    }
    else
    {
       $sql.=" WHERE ref_number LIKE :order_no";
       $condition=true;
    }
}

正如op在评论中所说的那样是

的解释
$sql.=" WHERE txn_date BETWEEN :from_date AND :to_date";

将此替换为

$sql.=" WHERE date(txn_date) BETWEEN date(:from_date) AND date(:to_date)";

ref_number = :order_no

而不是上面的一个类型将它转换为无符号整数,就像在if / else语句中的where where条件

CONVERT(ref_number,UNSIGNED INTEGER) = :order_no

答案 1 :(得分:1)

而不是

$arr[] = ":from_date => $from_date";

$arr['from_date'] = $from_date;

阅读有关php数组here的更多信息。

另外,我要做的是:

$sql = "SELECT * FROM test WHERE 1=1";

然后无需测试$condition,只需简单地连接到$sql