PDO:准备与bindvalue和% [英] PDO : prepare with bindvalue and like %

查看:77
本文介绍了PDO:准备与bindvalue和%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在各个网站上浏览了一个多小时,但无法解决自己的问题.

I've looked over an hour on various website but I couldn't solve my problem.

这是有效的代码:

$animes = array();
    $q = $this->_db->query('SELECT id, nom, nom_id FROM animes WHERE nom LIKE "%code%"');
    while ($data = $q->fetch(PDO::FETCH_ASSOC))
    {
        $animes[] = new Anime($data);
    }
    return $animes;

这是行不通的:

$animes = array();
$q = $this->_db->prepare('SELECT id, nom, nom_id FROM animes WHERE nom LIKE :n');
$q->bindValue(':n',"%code%",PDO::PARAM_STR);
    while ($data = $q->fetch(PDO::FETCH_ASSOC))
     {
         $animes[] = new Anime($data);
     }
return $animes;`

在此示例中,我使用%code%,但它将与$info一起使用,这是我检索到的$_POST值.

I use %code% in this example but it will be used with $info which is a $_POST value that I retrieve.

我该如何解决?

谢谢.

推荐答案

您没有execute().

绑定后,您需要执行然后提取:

after binding you need to execute then fetch:

$q->bindValue(':n',"%code%",PDO::PARAM_STR);
$q->execute();  
while ($data = $q->fetch(PDO::FETCH_ASSOC))

您可以像这样用php变量进行绑定:

you can bind like this with php variable:

$q->bindValue(':n','%'.$var.'%',PDO::PARAM_STR);

这篇关于PDO:准备与bindvalue和%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆