0

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 -->    
<?php 

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


if(empty($stmt))
{
    echo 'Nothing found';
}
else
{
echo 'found';
}



?>
<!-- DISPLAY RESULTS -->
    <tr>            <!-- Adding the first table row -->
        <th>Dog Park</th>   <!-- Adding the second table header -->
    </tr>
    <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 -->
    </tr>
        <?php } ?>

</table>

Example:
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'

  • $stmt->rowcount() is your friend. http://php.net/manual/en/pdostatement.rowcount.php – P. Gearman May 18 '16 at 14:49
  • 2
    You **really** need to look at how prepared statements are suppose to be used. http://php.net/manual/en/pdo.prepared-statements.php – chris85 May 18 '16 at 14:52
  • 2
    If you are going through the effort of using prepared statements, you should not be concatenating input variables into the query string, ESPECIALLY user-provided variables like from $_POST. – Mike Brant May 18 '16 at 14:54

3 Answers3

1

Your if structure should show 'found' because your query executed successfully, in this cases you can count rows for decide about this issue:

if($stmt->rowCount() == 0)
{
     echo 'Nothing found';
}
else
{
     echo 'found';
}
Majid Abbasi
  • 1,531
  • 3
  • 12
  • 22
1

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 ?");
$stmt->execute(array("%".$_POST['keyword']."%"));
$_SESSION['KEYWORD'] = $stmt->fetchAll(PDO::FETCH_COLUMN);

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

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

vp_arth
  • 14,461
  • 4
  • 37
  • 66
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • it will be bit better if you replace `%` in `$_POST['keyword']` by `[%]` – vp_arth May 18 '16 at 15:12
  • I don't really get it. You want to escape %? – Your Common Sense May 18 '16 at 15:13
  • Sure, if user send `50% width` to your script it match `50 shades of width` text too ;) – vp_arth May 18 '16 at 15:14
  • Got follwoing error message **PHP Parse error: syntax error, unexpected '[', expecting ')' in D:\users\n9692703\KEYWORD_SEARCH_RESULTS.php** at code **$stmt->execute(["%".$_POST['keyword']."%"]);** –  May 18 '16 at 15:15
  • Oh, no) just `str_replace('%', '[%]', $_POST['keyword'])` – vp_arth May 18 '16 at 15:15
  • @deluxenathan you should upgrade your PHP version, it's severily outdated. I edited the code to make it work with unsupported PHP version. – Your Common Sense May 18 '16 at 15:19
  • @vp_arth `str_replace('%', '\%', $_POST['keyword'])` you probably meant? – Your Common Sense May 18 '16 at 15:20
  • I'm sorry. This is T-Sql in my head. In Mysql it will some harder: `like ? escape '\'` in query and `str_replace('%', '\\%', $par)` in data. – vp_arth May 18 '16 at 15:22
  • `'\%'` is one char string, need `'\\%'`. All this conversation just for knowledge. I'm just confused, why nobody cares about this kind of injection? – vp_arth May 18 '16 at 15:26
  • @Your Common Sense OK, thanks for notifying about update. IF Statement seems to work but wont display table and data inside of it, If you look at bottom of my code, its a table, I tried putting that into the IF statement but **no** results are shown... any ideas?? –  May 18 '16 at 15:36
  • @vp_arth it is not actually an injection. entering simply "50" will give you exactly the same result. So, it's only a user experience. And if no % are expected in the data, there will be no harm at all – Your Common Sense May 18 '16 at 15:36
  • but if user search anything with percent sign he get bad UX – vp_arth May 18 '16 at 15:38
  • @deluxenathan, use `$row[0]` same as little above – vp_arth May 18 '16 at 15:41
  • @vp_arth exactly. But my answer was to the question "why nobody cares about this kind of injection?". – Your Common Sense May 18 '16 at 15:44
  • @vp_arth Still does not seem to solve my issue, data is still not being display in the table, even after putting for loop in IF statement –  May 18 '16 at 15:50
  • Thanks guys, you've solved my issue much appreciated. –  May 18 '16 at 16:02
0

I am not going to get into the SQL injection problem you have with your current code. You need to fix it, likely using parameters with your prepared statement, but that is another topic.

I would also say your KEYWORD.$i approach is an antipattern. Why not just have numerically-indexed array under $_SESSION['KEYWORD']?

$_SESSION['KEYWORD'] = array();
$stmt = $conn->prepare("SELECT DISTINCT dog_park_name FROM dog_park.items WHERE dog_park_name LIKE '%{$KEYWORD}%'");
if($stmt) {
    $result = $stmt->execute();
    if($result) {
        while($row= $stmy->fetch() {
            $_SESSION['KEYWORD'][] = $row[0];
        }
    }
}  
if(count($_SESSION['KEYWORD']) === 0) {
    echo 'Nothing found';
} else {
    echo 'found';
}
Mike Brant
  • 70,514
  • 10
  • 99
  • 103