$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]:无效的参数编号:参数未定义
怎么了
最佳答案
在变量$ 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条件中,都将上述类型强制转换为无符号整数,如下所示
CONVERT(ref_number,UNSIGNED INTEGER) = :order_no
关于php - PHP PDO动态查询构建,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29960014/