Hi everyone…
Could someone be so kind as to explain to me why my code cannot work?
I’m trying to build a product page, where a search query is listed out on the same page.
So while constructing how the products will be echoed out, I first check if isset($_GET[‘search’]) to see if the user simply landed on the page or if he’s actually searching for something.
The code:
$sql = 'SELECT * FROM listings';
if (isset($_GET['search'])) {
//Users can search by:
//Title or Description or Vendor Code
$sql .= " WHERE L_TITLE LIKE ? OR v_ref LIKE ? OR L_DESCRIPT LIKE ? "; //check if there is any search queries in the url
//MySQL uses short-circuit evaluation for the OR operator. In other words, MySQL stops evaluating the remaining parts of the statement when it can determine the result.
$search_param = $_GET['search'];
$passThis = "%" . $search_param . "%";
$sql .= ' ORDER BY L_OPEN_DATE '; //learn how to search by relevance instead
} else {
$sql .= 'ORDER BY rand(700)'; //refresh this seed every 24hrs using a user-session
}
$sql .= ' LIMIT 200 ';
$stmt = $conn->prepare($sql);
$stmt->bind_param('sss', $passThis, $passThis, $passThis);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
//assign rows to variables
//echo out product list here
}
The trouble I’m faced with is when I try to use prepared statements on the search value… The page works (lists all the products with the keyword the user typed in), however, I can’t view the ‘landing’ page any longer. In other words, if I land on the page without actually searching for anything, it does not list any products and gives this error:
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in...
Which, I assume, means that the actual query is failing, because it’s looking to bind paramaters it cannot find (since it’s out of the “if” statement).
How, pray, can I modify this code to use prepared statements while also displaying the search results on the same page?