deluxenathan deluxenathan - 5 months ago 13x
SQL Question

PHP PDO Display message if no results are found in search

I am trying to set an 'No Results Found' message when no search results are found after executing a MySQL 'LIKE' Query

I have the following code below:

I have an if statement just to test to see if an error message will work but I seem to get the output of the else statement 'found'

<table class="center"> <!-- Creating a table with the class of 'center' -->
<!-- SEARCH FORM -->

$KEYWORD = $_POST['keyword'];
$stmt = $conn->prepare("SELECT DISTINCT dog_park_name FROM dog_park.items WHERE dog_park_name LIKE '%{$KEYWORD}%'");
for($i=0; $row = $stmt->fetch(); ){
$_SESSION["KEYWORD".$i] = $row[0];

echo 'Nothing found';
echo 'found';

<tr> <!-- Adding the first table row -->
<th>Dog Park</th> <!-- Adding the second table header -->
<tr> <!-- Adding the second table row -->
<td><a href="individual_item_page.php?keyword='<?php echo $row[$i] ?>' " ><?php echo $row[$i] ?></a></td> <!-- Add the second cell on the second row -->
<?php } ?>



If a user searches a keyword, and no results are found from that keyword, I am trying to get a message saying 'No Results found'


To make a Mike Brant's answer a proper one:

$stmt = $conn->prepare("SELECT DISTINCT dog_park_name FROM items WHERE dog_park_name LIKE ?");
$_SESSION['KEYWORD'] = $stmt->fetchAll(PDO::FETCH_COLUMN);

  <tr><th>Dog Park</th></tr>
 <?php foreach($_SESSION['KEYWORD'] as $word):?>
    <tr><td><?php echo $word?></td></tr>
 <?php endforeach?>
} else {
    echo 'Nothing found';

So in other words, you always have the query results to tell whether you have any results.