Search code examples
phpmysqlsearch-engine

How to create a simple Mysql search engine


I've written this simple code to retrieve a value of a table which starts with a variable coming from a POST method: i know that in my table there is only that value, so i want to retrieve the unique value in a string variable:

... 
$query = "SELECT * FROM news WHERE contenuto LIKE :contenuto%"; 
$query_params = array(
      ':contenuto' => $_POST['contenuto']
);
try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}catch (PDOException $ex){
}
$row = $stmt->fetch();
$this = $row['contenuto'];
echo $this;
...

But this code doesn't work because nothing in showed by echo.. any help?


Solution

  • The % wildcard should be in the bound variable and not the prepared statement

    $query = "SELECT * FROM news WHERE contenuto LIKE :contenuto"; 
    $query_params = array(
          ':contenuto' => $_POST['contenuto'] . '%'
    );