Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO : prepare with bindvalue and like %

Tags:

sql

php

pdo

prepare

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.

like image 801
Jérôme B Avatar asked Oct 16 '25 13:10

Jérôme B


1 Answers

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);
like image 104
Awlad Liton Avatar answered Oct 19 '25 03:10

Awlad Liton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!