搜索php.in,php – 使用IN指令搜索预准备语句

本文探讨了在使用预准备语句时如何正确处理参数绑定的问题,避免SQL注入风险,并通过实例展示了如何使用PHP的mysqli及PDO实现动态参数的安全绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

预准备语句没有参数,因为您在准备之前已将列表插入到语句中.

$array=array("item1","item2","item3","item4");

//This is dynamically filled, this is just an example

$in_list = "'".implode("','",$array)."'";//that's why i use implode

$stmt = $this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements where type IN ('.$in_list.')');

此时,您创建的SQL语句是:

SELECT libelle,activite,adresse,tel,lat,lng

FROM etablissements where type IN ('item1','Item2','Item3','Item4')

由于该语句没有参数,因此mysqli_stmt :: bind_param失败.不是将项插入到语句中(易于注入),而是插入一串参数,然后绑定值(必须保持独立).

$array=array("item1","item2","item3","item4");

if (count($in_list) > 0) {

$query = $this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements WHERE type IN (' . str_repeat('?, ', count($in_list)-1) . '?)');

$args = $in_list;

array_unshift($args, str_repeat('s', count($in_list)));

call_user_func_array(array($query, 'bind_param'), $args);

$query->execute();

$query->bind_result($libelle,$activite,$adresse,$tel,$lat,$lng);

}

PDO的绑定接口更直接.

$array=array("item1","item2","item3","item4");

if (count($in_list) > 0) {

$query = $this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements WHERE type IN (' . str_repeat('?, ', count($in_list)-1) . '?)');

foreach ($in_list as $i => $arg) {

// query params are 1-based, so add 1 to the index

// PDO::PARAM_STR is the default type, so no need to pass 3rd arg

$query->bindValue($i+1, $arg);

}

$query->execute();

// no need to bind the result

}

实际上,使用PDO可以更简单,因为PDOStatement::execute可以获取参数值列表:

$array=array("item1","item2","item3","item4");

if (count($in_list) > 0) {

$query = $this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements WHERE type IN (' . str_repeat('?, ', count($in_list)-1) . '?)');

$query->execute($in_list);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值