0

Well, I am making a game website and I have a search bar where the user types the game he wants to find. I have something like this (this is a test, don't need to block sql injection):

<?php

if ($_REQUEST['search']){

    $searched = $_POST['searched'];
    $gamesearched = mysql_query("SELECT * from games WHERE name like '%$searched%'");

    while($write=mysql_fetch_array($gamesearched)){
    echo "Found it!" 
    }

}else{
echo "Search something";
}


?>

I can't use an else to the while statement so how would I do to show something like "No games where found".

I am trying to use this but doesn't work :P

while(($write=mysql_fetch_array($gamesearched)) != null){
echo "found";
}else{
echo "not found";
}
John Lemon
  • 81
  • 1
  • 5

3 Answers3

5

Why not wrap an if statement around your while statement?

if ($_REQUEST['search']){

    $searched = $_POST['searched'];
    $gamesearched = mysql_query("SELECT * from games WHERE name like '%$searched%'");

    if(mysql_num_rows($gamesearched) > 0){

         while($write=mysql_fetch_array($gamesearched)){
         echo "Found it!" 
         }

     } else {

          echo "not found";

     }

}
ShoeLace1291
  • 4,551
  • 12
  • 45
  • 81
  • Notice the last closing bracket } I added at the end, in case you tried it already. Also, the mysql num rows function will get the number of results that match your query and can be used in any SELECT query. – ShoeLace1291 Jun 15 '13 at 09:15
2

as you noticed, you can't write else after a while because it's a loop and not a control-structure like if. even if the syntax looks very similar, this are completely different things.

one possibility to solve your problem would be to use a boolean variable:

$found = false
while(...){
  $found = true;
  // something more here
}
if(!$found){
  echo "nothig found";
}
oezi
  • 51,017
  • 10
  • 98
  • 115
-4

if you only seek one single item, you can break from a loop early

while(..) {
  ..
  if ( found_smth ) break;
}
Honk der Hase
  • 2,459
  • 1
  • 14
  • 26