栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用IN指令搜索准备好的语句

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用IN指令搜索准备好的语句

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/431639.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号