-1

I created search function for my blog. Source of my View -

<?php
if (!empty($query)):
    foreach ($query as $item):
        echo '<h2><a href="/article/' . $item['slug'] . '">' . $item['virsraksts'] . '</a></h2>';
        echo '<p>' . nl2br($item['saturs']) . '</p>';
    endforeach;
else:
    echo 'Nothing found!';
endif;
?>

When I submit a wrong search query, script want to show the error message 'Nothing found!' but this message do not appear. Why the error message don't appear?

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
PelnaE
  • 69
  • 1
  • 10
  • 2
    Because $query isnt empty. Just as you stated it. – TJHeuvel Oct 26 '11 at 12:53
  • 1
    Someone still uses the alternative PHP syntax, that's surprising. But on the topic: There is no way to answer your question unless we know what's in your $query variable. Try putting print_r($query); in front of "if" statement to check what the actual value of it is. Both when there are results and when there aren't any – Ivan Oct 26 '11 at 12:55
  • 2
    @Ivan I'm guessing it's part of a view, but usually you jump out of the PHP tags – gawpertron Oct 26 '11 at 12:57
  • @gawpertron exactly what I was thinking... – acm Oct 26 '11 at 13:00

2 Answers2

1

because, as others have already stated, if (!empty($query)): isn't checking the result of the query. It's checking whether the variable $query is empty or not.

I think what you want to do is something like this:

if (mysql_num_rows($query) > 0) {
   // do something here
}

where $query is the returned result of a php mysql_query() call.

http://php.net/manual/en/function.mysql-num-rows.php

rgin
  • 2,291
  • 4
  • 24
  • 32
0

use var_dump($query) before "IF" statement to check if there is something in $query array

  • When I type, for example 'word' and var_dump shows - `object(Database_MySQL_Result)#23 (7) { ["_internal_row":protected]=> int(0) ["_query":protected]=> string(99) "SELECT * FROM ieraksti WHERE virsraksts like '%word%' OR slug like '%word%' OR saturs like '%word%'" ["_result":protected]=> resource(67) of type (mysql result) ["_total_rows":protected]=> int(0) ["_current_row":protected]=> int(0) ["_as_object":protected]=> bool(false) ["_object_params":protected]=> NULL }` – PelnaE Oct 26 '11 at 13:13
  • maybe you should count the number of rows on the result rather than check that the object is empty – gawpertron Oct 26 '11 at 13:23