Sarfaraz Ansari
Sarfaraz Ansari

Reputation: 129

Trying to run two sql queries under if else condition in php?

I have tried to search for solutions but can't find one. On my php page I am trying to search records on two conditions, if user enters something in search box then show according to that and if he doesn't searches anything then display records from table.

I am getting all records but unable to get records when i search for them using their name.

 <?php
 if(isset($_POST['search']))
 {
 $name=$_POST['src'];
 $qry1=mysqli_query($connection,"select * from test_history where 
 username='$name'");
 }
 else
 {
 $qry1=mysqli_query($connection,"select * from test_history");
 $counter=0;
 while($ftc=mysqli_fetch_array($qry1))
 echo
 '<tr>

 <td align="center"> '.++$counter.' </td> 
 <td> '.$ftc['username'].' </td>    
 <td> '.$ftc['enrollment'].' </td> 
 <td> '.$ftc['test_cat'].' </td> 
 <td> '.$ftc['test_name'].' </td> 
 <td> '.$ftc['score'].'% </td> 
 <td> '.$ftc['test_date'].' </td> </tr>';

 }
  if(isset($_POST['submit']))
  {
    $dlt=mysqli_query($connection,"delete from test_history");
  }
 ?> 

Upvotes: 0

Views: 1810

Answers (1)

Mohammed Q. Hussain
Mohammed Q. Hussain

Reputation: 46

Probably because the table that shows the result is inside "else" block. Try to get it outside.

     <?php
     if(isset($_POST['search']))
     {
     $name=$_POST['src'];
     $qry1=mysqli_query($connection,"select * from test_history where 
     username='$name'");
     }
     else
     {
     $qry1=mysqli_query($connection,"select * from test_history");
     $counter=0;
     }

// ... //

     while($ftc=mysqli_fetch_array($qry1))
     echo
     '<tr>

     <td align="center"> '.++$counter.' </td> 
     <td> '.$ftc['username'].' </td>    
     <td> '.$ftc['enrollment'].' </td> 
     <td> '.$ftc['test_cat'].' </td> 
     <td> '.$ftc['test_name'].' </td> 
     <td> '.$ftc['score'].'% </td> 
     <td> '.$ftc['test_date'].' </td> </tr>';

// ... //

      if(isset($_POST['submit']))
      {
        $dlt=mysqli_query($connection,"delete from test_history");
      }
     ?> 

What Happened After Moving The Portion of Code

Anything inside "else" block will be executed when the negation of "if" condition is met, that is, isset($_POST['search']) is "false". The portion of the code which is responsible for displaying the data was inside "else" block, which means the data will be shown only if isset($_POST['search']) returns false.

Obviously, that's not you want. You always want to show the data and you want to change the query according to $_POST['search'] value. The second requirement is implemented by if statement. Please refer to http://php.net/manual/en/control-structures.else.php

Upvotes: 2

Related Questions