gpt4 book ai didi

PHP PDO 动态查询构建

转载 作者:太空宇宙 更新时间:2023-11-03 11:59:52 25 4
gpt4 key购买 nike

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

执行此查询时会显示类似

的警告

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

有什么问题吗?

最佳答案

在变量 $arr 中,你应该像这样替换所有关联索引

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

此外,将公共(public)代码移到外部 block 而不是 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 PDO 动态查询构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29960014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com