Php PDO中的动态SQL和bindParam
我的情况是这样的:Php PDO中的动态SQL和bindParam,php,pdo,Php,Pdo,我的情况是这样的: if ( $level == 1 ) { $type = '0'; } elseif ( $level == 2 ) { $type = '1'; } elseif ( $level == 3 ) { $type = '(2 or type = 1)'; // This part does not work. } elseif ( $level == 10 ){ $type = '3';
if ( $level == 1 ) {
$type = '0';
} elseif ( $level == 2 ) {
$type = '1';
} elseif ( $level == 3 ) {
$type = '(2 or type = 1)'; // This part does not work.
} elseif ( $level == 10 ){
$type = '3';
} else {
return false;
}
$sqlFindParent = 'select count(id) as parent from datable where id = :parent and uType = :type and countryCode = :countryCode';
$findParent = $conn->prepare($sqlFindParent);
$findParent->bindParam(':type',$type);
$type是动态的。当我绑定它时,当涉及到
elseif($level==3)
时,它不起作用,因为那里有或
。当然,我可以在中使用,但您有更好的方法使用或
本身吗?当您绑定param时,以一种简化的方式告诉数据库“这不是语句的一部分,而是它的一个参数值”。您的数据库不会将其作为SQL的一部分进行处理,而是作为一个值进行处理,因此从理论上讲,您最终会得到如下结果:
select
count(id) as parent
from
datable
where
id = '123'
and uType = '(2 or type = 1)'
and countryCode = 'US'
请注意值周围的“
,它不会那样工作,解决方案确实是使用IN语句
注意:实际上,在prepare/execute执行流中,在绑定参数并执行语句时,数据库甚至没有使用SQL语句字符串,而是使用查询的内部表示形式。我编写这个示例只是为了让您更清楚地了解为什么代码不起作用,但事实并非如此。它不起作用,因为bindParam作为方法的名称表明binds param不是语句。
我想到的解决办法是总是绑定两个参数,一个永远不可能存在的参数
$sqlFindParent = 'select count(id) as parent from datable where id = :parent and (uType = :type or uType = :type2) and countryCode = :countryCode';
然后将ifs更改为“切换”
$type = 0; $type2=-1;
switch($level)
{
case 1:
$type = 0;
break;
case 2:
$type = 1;
break;
case 3:
$type = 2;
$type2 = 3;
break;
}
和约束
$findParent->bindParam(':type',$type, PDO::PARAM_INT);
$findParent->bindParam(':type2',$type2, PDO::PARAM_INT);
当你从逻辑的角度来看它的时候。你有两个变量
在案例1,2中
当至少有一个变量为true时,语句将为true,type2的默认值始终为false,因此当语句的第一部分为true时,语句将为true。所以脚本中不会有任何更改
在案例3中
其中一个语句部分必须为true,这样当它找到type或type2时,它将返回正确的uest结果。它不起作用,因为它绑定的参数不是语句。我认为你应该寻找某种ORM,然后绑定参数。
中的与或相同?他提到他不想在()中使用,
,所以我发布了另一种解决方案。@Norman:现在假设明天你必须用3个案例,而不是2个案例。然后是50箱。您的代码将不可维护<在
中,code>是专门为此而设计的,没有理由不使用它。如果您认为它在性能方面效率较低,则情况并非如此。如果(2,3,4)
中的与中的(a=2或a=3或a=4)
相同,我不认为它效率较低,但可读性较差。