PDO search database using LIKE

前端 未结 4 1514
攒了一身酷
攒了一身酷 2020-12-18 08:43

I am trying to make a small search function to look at database using this code:

$searchQ = \'Li\';
$query = $connDB->prepare(\'SELECT * FROM topic WHERE          


        
4条回答
  •  余生分开走
    2020-12-18 09:02

    Remove the quotes from the placeholder and add a colon before your bind reference:

    $query = $connDB->prepare('SELECT * FROM topic WHERE topic_name LIKE :keywords');
    $query->bindValue(':keywords', '%' . $searchQ . '%');
    

    Here's my text example:

    SQL

    CREATE TABLE IF NOT EXISTS `items` (
      `id` mediumint(9) NOT NULL auto_increment,
      `name` varchar(30) NOT NULL,
      PRIMARY KEY  (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
    
    
    INSERT INTO `items` (`id`, `name`) VALUES
    (1, 'apple'),
    (2, 'orange'),
    (3, 'grape'),
    (4, 'carrot'),
    (5, 'brick');
    

    PHP

    $keyword='ap';
    $sql="SELECT * FROM `items` WHERE `name` LIKE :keyword;";
    $q=$dbh->prepare($sql);
    $q->bindValue(':keyword','%'.$keyword.'%');
    $q->execute();
    while ($r=$q->fetch(PDO::FETCH_ASSOC)) {
        echo"
    ".print_r($r,true)."
    "; }

    Output

    Array
    (
        [id] => 1
        [name] => apple
    )
    Array
    (
        [id] => 3
        [name] => grape
    )
    

提交回复
热议问题