0

I'm trying to build a search function for my database but it's not returning any results. This is what I got:

$searchQuery = $_GET[q];
$search = $conn->prepare('SELECT * FROM articles WHERE title LIKE \'%:query%\' OR content LIKE \'%:query%\'');
$search->bindParam(':query', $searchQuery, PDO::PARAM_STR);

$search->execute();
$searchResult = $search->fetchAll();

foreach($searchResult as $row) {
    print "<h2><a href=\"view.php?a=" . $row[id] . "\">" . $row[title] . "</a></h2>";
}

When I execute the SQL statement directly with $conn->query('SELECT...') it works perfectly, but not with the prepared statement. I don't get an error, it just doesn't load any results. What am I missing?

Edit: moved the wildcards from the prepared statements to the bind variable like this:

$searchQuery = '%' . $_GET[q] . '%';
$search = $conn->prepare('SELECT * FROM articles WHERE title LIKE :query OR content LIKE :query');

Works perfectly now. Thank you!

Besasam
  • 47
  • 1
  • 11

0 Answers0