Home  >  Article  >  Backend Development  >  pdo绑定数据不对

pdo绑定数据不对

WBOY
WBOYOriginal
2016-06-06 20:32:591241browse

<code>php</code><code>$sql = 'SELECT * FROM user WHERE id IN (:ids)';
$pdo = new PDO('mysql:host=localhost;dbname=test','root','');
$sth->prepare($sql);
$sth->execute([':ids'=>'1,2,3,4,5']);
$users = $sth->fetchAll(PDO::FETCH_ASSOC);
//然后。。。就没有然后了。。。数据为空
</code>

经过我的一番测试,发现如果SQL是可以地:

<code>sql</code><code>SELECT * FROM user WHERE id IN (1,2,3,4,5)
</code>

但是PDO绑定数据的时候会把SQL变为酱紫(好吧,我猜的o(╯□╰)o):

<code>sql</code><code>SELECT * FROM user WHERE id IN ('1,2,3,4,5')
</code>

这特么肯定就不行了啊。。。各位大大可有解决办法,既要能绑定数据,又要不出错?

注意,以上只是简单说明,我的实际情况还要复杂得多。。。但问题我确定过了,就是这个(只有在条件为IN时且IN传入了2+才会出错)。


@netingcn 我的这种绑定方式是可以的,只是被PDO当成一个参数值了,而我其实是5个参数值。

回复内容:

<code>php</code><code>$sql = 'SELECT * FROM user WHERE id IN (:ids)';
$pdo = new PDO('mysql:host=localhost;dbname=test','root','');
$sth->prepare($sql);
$sth->execute([':ids'=>'1,2,3,4,5']);
$users = $sth->fetchAll(PDO::FETCH_ASSOC);
//然后。。。就没有然后了。。。数据为空
</code>

经过我的一番测试,发现如果SQL是可以地:

<code>sql</code><code>SELECT * FROM user WHERE id IN (1,2,3,4,5)
</code>

但是PDO绑定数据的时候会把SQL变为酱紫(好吧,我猜的o(╯□╰)o):

<code>sql</code><code>SELECT * FROM user WHERE id IN ('1,2,3,4,5')
</code>

这特么肯定就不行了啊。。。各位大大可有解决办法,既要能绑定数据,又要不出错?

注意,以上只是简单说明,我的实际情况还要复杂得多。。。但问题我确定过了,就是这个(只有在条件为IN时且IN传入了2+才会出错)。


@netingcn 我的这种绑定方式是可以的,只是被PDO当成一个参数值了,而我其实是5个参数值。

pdo不支持这种数组绑定。很早就有人提过类似的问题,详情请戳这里:

http://segmentfault.com/q/1010000000119523

附上我临时解决方案,期待哪位大大给出更好的解决办法:

<code>$ids = [1,2,3,4,5];//外部传入的数组
$sql = 'SELECT * FROM user WHERE id IN (';
foreach($ids as $id){
    $sql.=intval($id).',';
}
$sql = rtrim($sql ,',') . ')';
$pdo = new PDO('mysql:host=localhost;dbname=test','root','');
$sth->prepare($sql);
$sth->execute();
$users = $sth->fetchAll(PDO::FETCH_ASSOC);
</code>

要不别绑定,要不拆成字符串再绑定吧

http://php.net/manual/zh/pdostatement.execute.php

<code>$ids = array(1, 2, 3, 4, 5);
$in  = implode(',', array_fill(0, count($ids), '?')); // 生成问号占位符
$sth = $dbh->prepare("SELECT * FROM table WHERE id IN ($in)");
$sth->execute($ids);
</code>

使用问号占位符时,execute绑定一个索引数组,所有的值作为 PDO::PARAM_STR 对待.
使用命名占位符时,execute绑定一个关联数组,所有的值作为 PDO::PARAM_STR 对待.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn