PDO : prepare with bindvalue and like %

两盒软妹~` 提交于 2020-01-14 01:38:32

问题


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

So here is the code that works:

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

And here is the one that doesn't work :

$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;`

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

How can I solve it ?

Thank you.


回答1:


you did not 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))

you can bind like this with php variable:

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


来源:https://stackoverflow.com/questions/22154246/pdo-prepare-with-bindvalue-and-like

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!