gpt4 book ai didi

PHP PDO 查询,具有从数组中获取的多个条件

转载 作者:行者123 更新时间:2023-11-30 01:31:45 27 4
gpt4 key购买 nike

我想在单个查询中执行一些条件。基本查询:

$query = "select * from table1
inner join
table2 on table1.id=table2.id
where
".$condition."
limit 0,100;";

我有要查询的值数组:

$Var = array(
1 => array('name' => 'somename1','value' => 'somevalue1'),
2 => array('name' => 'somename2','value' => 'somevalue2'),
3 => array('name' => 'somename3','value' => 'somevalue3'),
4 => array('name' => 'somename4','value' => 'somevalue4')
)

现在正在循环

foreach($Var as $Array){  
$condition .= '(T1_column1 = '.$Array['name'].' and T2_column1 = '.$Array['value'].') or ';
}

最终结果:

$query = "select * from table1
inner join
table2 on table1.id=table2.id
where
(T1_column1 = somename1 and T2_column1 = somevalue1) or
(T1_column1 = somename2 and T2_column1 = somevalue2) or
(T1_column1 = somename3 and T2_column1 = somevalue3) or
(T1_column1 = somename4 and T2_column1 = somevalue4)
limit 0,100;";

有没有办法使用 PDO 做同样的事情:准备、绑定(bind)值、执行?或者foreach循环中的bindValue有同样的效果吗?我该怎么做?

最佳答案

这是 PDO bind unknown number of parameters? 的重复项

为了您的方便,这是 Paystey 答案中的代码,经过修改以适合您的示例:

$sql = 'SELECT * FROM table1
INNER JOIN table2 ON table1.id=table2.id
WHERE ';
foreach($Var as $Array)
{
$sql .= '(T1_column1 = ? and T2_column1 = ?) or ';
$binds[] = $Array['name'];
$binds[] = $Array['value'];
}
$prep = $db->prepare(substr($sql,0,-3) . 'limit 0,100');
$i = 0;
foreach($binds as $bind){
$prep->bindValue(++$i, $bind);
}
$prep->execute();

未经测试。

关于PHP PDO 查询,具有从数组中获取的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17370821/

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