PDO search database using LIKE

前端 未结 4 1507
攒了一身酷
攒了一身酷 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 08:46

    showdev thanks you tutorial

    SQL

    CREATE TABLE IF NOT EXISTS 'news' 
    (`id` int(9) NOT NULL auto_increment, 
      `title` text NOT NULL, 
      PRIMARY KEY  (`id`)
    ) 
    ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
    insert into `items` (`id`, `title`) VALUES
    (1, 'news title'),
    (2, 'news title 2');
    

    PHP

    $connection = new PDO('mysql:host=localhost;dbname=YOUR_DATABASE_NAME','root','');
    if (isset($_GET['store'])) {
    $store = $_GET['store'];
    if(!empty($store)){//condition you the remove karakter
        $q=$connection->prepare("SELECT title FROM tbl_nes WHERE title LIKE :store");
        $q->bindValue(':store','%'.$store.'%'); 
        $q->execute();
        while ($r = $q->fetch(PDO::FETCH_OBJ)) { 
            echo $r->title,"<br>";
        }         
    }
    } 
    

    OUTPUT

    1.news title
    2.news title 2 ....
    
    0 讨论(0)
  • 2020-12-18 08:48

    You need to pass a single variable to bind_param not a concatenated string, because parameter two must be a reference not a value.

    $keyword_to_search = '%' . $searchQ . '%';
    $query->bindValue('keywords', $keyword_to_search); 
    
    0 讨论(0)
  • 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"<pre>".print_r($r,true)."</pre>";
    }
    

    Output

    Array
    (
        [id] => 1
        [name] => apple
    )
    Array
    (
        [id] => 3
        [name] => grape
    )
    
    0 讨论(0)
  • 2020-12-18 09:12

    You can only bind data literals. Try

     $searchQ = '%Li%'; OR  $searchQ = '%'.Li.'%';
    $query = $connDB->prepare('SELECT * FROM topic WHERE topic_name LIKE :keywords');
    $query->bindValue('keywords', $searchQ );
    
    0 讨论(0)
提交回复
热议问题