Diasline Diasline - 5 months ago 19
PHP Question

Searching data MongoDB/php

I can display collections from mongodb acording the input entry using php with codes below. When data entered in input field is not matched with any collection i want to display **This name is not found in database **. I got stuck here, the message can't display.

require_once('mongo_config.php');
$searchtext = $_GET["name"];
$get_users1 = $c_users->find(array('firstname'=> array('$regex' => $searchtext)));

if(empty($get_users1))
{
echo 'This name is not found in database !';
}
if(!empty($get_users1)){
echo '<table>';
echo '<tr><th>firstname</th><th>lastname</th><th></th><th></tr>';
foreach($get_users1 as $user)
{
echo '<tr>';
echo '<td>' . $user['firstname'] . '</td>';
echo '<td>' . $user['lastname'] . '</td>';
echo '<td><a href="update_user.php?edit=' . $user['_id'] . '">Modifier</td>';
echo '<td><a href="delete_user.php?delete='.$user['_id'].'" onclick="return confirm(\'Do you really want to delete this user ?\')">Supprimer</td>';
echo '</tr>';
echo '</tr>';
}
echo '</table>';
}


I would like to get help to display the message when no data is found in database.
thanks

Answer

Why not use else?

if($c_users->count()>0){
  echo '<table>
            <tr>
                <th>firstname</th>
                <th>lastname</th>
                <th></th><th>
            </tr>';
   foreach($get_users1 as $user)
   {
      echo '<tr>
             <td>' . $user['firstname'] . '</td>
             <td>' . $user['lastname'] . '</td>
             <td><a href="update_user.php?edit=' . $user['_id'] . '">Modifier</td>
             <td><a href="delete_user.php?delete='.$user['_id'].'" onclick="return confirm(\'Do you really want to delete this user ?\')">Supprimer</td>
            </tr>';
   }
        echo '</table>';
} else {
    echo 'This name is not found in database !';    
}