Peppegiuseppe
Peppegiuseppe

Reputation: 183

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?

Upvotes: 1

Views: 81

Answers (2)

FuzzyTree
FuzzyTree

Reputation: 32392

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'] . '%'
);

Upvotes: 2

Mureinik
Mureinik

Reputation: 310983

You're mixing bind parameters with literals. Try this on for size:

$query = "SELECT * FROM news WHERE contenuto LIKE CONCAT(:contenuto, '%')"; 

Upvotes: 0

Related Questions