-3

When I click on search button without entering any text in textbox it gives me "Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, string given" this error, how can I sort out this issue,here is my code any help will be appreciated

<?php
$title ="Manage Page";
include "includes/home_page_header.php";
?>
<?php
$error_array = array();
$count =1;
$firstName = $lastName = $email = $status =$res_users = $checkbox ="";

if(isset($_POST['Search']))
{
    $firstName = $_POST['firstName'];
    $lastName  = $_POST['lastName'];
    $email     = $_POST['email'];
    $status    = $_POST['status'];      


if($firstName !="")
{
    $sql_users ="SELECT * FROM `users` WHERE `firstName` LIKE '$firstName'";
}
else if($lastName !="")
{   
    $sql_users ="SELECT * FROM `users` WHERE `lastName` LIKE '$lastName'";
}
else if($email !="")
{   
    $sql_users ="SELECT * FROM `users` WHERE `email` LIKE '$email'";
}
else if($firstName !="" && $lastName !="")
{
    $sql_users ="SELECT * FROM `users` WHERE `firstName` LIKE '$firstName' AND `lastName` LIKE '$lastName'";
}
else
{
    $sql_users = "SELECT * FROM `users`";
}   

if(isset($_GET['user_id']))
{
    $user_id = $_GET['user_id'];

    $sql_users = "DELETE from `users` WHERE user_id=".$user_id;

if ($link->query($sql_users) == TRUE)
{
     $error ="Record deleted successfully"; 
     array_push($error_array,$error);
}
if ($link->query($sql_users) == FALSE) 
{
    $error = "Your Abort Delete operation";
    array_push($error_array,$error);
}
}

if($status == "Active")
{
    $sql_users= "SELECT * FROM `users` WHERE `status` LIKE 'Active'";
    $res_users = mysqli_query($link,$sql_users);

    if($res_users && mysqli_num_rows($res_users) > 0)
    {           
        while($log_row_users = mysqli_fetch_assoc($res_users))                              
        {
           $status = $log_row_users["status"];                  
        }
    }
}
if($status == "Inactive")
{
    $sql_users= "SELECT * FROM `users` WHERE `status` LIKE 'Inactive'"; 
    $res_users = mysqli_query($link,$sql_users);

    if($res_users && mysqli_num_rows($res_users) > 0)
    {           
        while($log_row_users = mysqli_fetch_assoc($res_users))                              
        {
           $status = $log_row_users["status"];          
        }
    }
}
$res_users = mysqli_query($link ,$sql_users);


}
if(isset($_POST['delete_all']))
{

}

?>
<script>
$(document).ready(function()
{
    $(".delete_button").on('click',function()
    {
        var result =confirm("Are you sure you want to delete ?");
        if(result)
        {
            return true;
        }
        else
        {
            return false;
        }
    });
});
//function wantTodelete(user_id)
//{
//  return confirm("Are you sure you want to delete ?");
//}


$(document).ready(function()
{
    $("#checkAll").change(function () {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
});
});

</script>
<table border="1px" class="manage_table">
<form name="listingForm" action="" method="post">
<tr>
<?php
if($error_array !=0)
{
    foreach($error_array as $value)
    {
        echo "<tr style='color:green;'><td></td><td> ". $value. "</td></tr>";   
    }
}
?>
</tr>
<tr>
<td></td>
<td><input type="text" name="firstName"></td>
<td><input type="text" name="lastName"></td>
<td><input type="text" name="email"></td>
<td>
<select name="status">
<option>Select Status </option>
<option value="Active"   <?php echo $status;?>>Active     </option>
<option value="Inactive" <?php echo $status;?>>Inactive   </option>
</select>
</td>
<td><input style="width:135px" type="submit" name="Search" value="Search"></td>
<td><input type="submit" id="delete_all" name="delete_all" value="Delete All" onclick="return deleteAll();" /></td>
</tr>
<tr>
<th>Sr.No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Status</th>
<th>Action</th>
<th><input type="checkbox" id="checkAll" name="check_all[]"/></th>
</tr>
<?php                       
if($log_row_users = mysqli_fetch_assoc($res_users))                             
{            
     $user_id      = $log_row_users['user_id'];  
     $firstName    = $log_row_users['firstName'];
     $lastName     = $log_row_users['lastName'];
     $email        = $log_row_users['email'];
     $status       = $log_row_users['status'];

?>
<tr>
<td><?php echo $count++  ;?></td>
<td><?php echo $firstName;?></td>
<td><?php echo $lastName ;?></td>
<td><?php echo $email    ;?></td>
<td>
<?php 
if($status == "Active")
{
    echo "<b style='color:#3CF'>".$status."</b>";
}
 if($status == "Inactive")
{
    echo "<b style='color:#F00'>".$status."</b>";
};
?>
</td>
<td>
<a style="margin-left:25px" href="http://localhost/sample/home_page_edit.php?user_id=<?php echo $user_id;?>" onclick="redirectMe();" name="redirect" id="redirect"><img src="images/pencil.png" /></a>


<a style="margin-left:35px"  href="http://localhost/sample/home_page_manage.php?user_id=<?php echo $user_id;?>" name="delete_button" class="delete_button" ><img src="images/delete.png" /></a>
</td>
<th>
<input name="checkbox[]" type="checkbox" id="checkbox[]" class="checkbox">
</th>
</tr>
</form>
<?php
}
?>
</table>
<?php
include "includes/home_page_footer.php";
?>
Dharman
  • 30,962
  • 25
  • 85
  • 135
Shanky
  • 85
  • 1
  • 10
  • it should be `$result = mysqli_query($sql); while($row = mysqli_fetch_array($result)): [...] endwhile;`, however, maybe your query returns an empty result so its causing errors? check that your results are not equal to null before fetching them. Note, you have so many injection points, search how to prevent SQLi injections. For speed queries, you can do: `foreach($db->query($sql) as $row): [...] endforeach;` – Jaquarh Apr 04 '16 at 11:12

3 Answers3

3

Try this one it will help you

 if(isset($_REQUEST['Search']))
    {
        $q = "SELECT * FROM users WHERE user_id!='' ";

        $firstName  = $_REQUEST['firstName'];
        $lastName   = $_REQUEST['lastName'];
        $email      = $_REQUEST['email'];
        $status     = $_REQUEST['status'];

        $temp='';
        if(!empty($firstName))
        {
            $temp.=" AND ";
            $temp.="firstName LIKE '%$firstName%'";
        }

        if(!empty($lastName))
        {
            $temp.=" AND ";
            $temp.="lastName LIKE '%$lastName%'";
        }

        if(!empty($email))
        {
            $temp.=" AND ";
            $temp.="email LIKE '%$email%'";
        }

        if(!empty($status))
        {
            $temp.=" AND ";
            $temp.="status LIKE '$status'";
        }

        $qry = $q. $temp. " order by user_id ASC";
    }
    else
    {
        $qry =  "SELECT * FROM users order by user_id DESC";
    }
Pargunan
  • 65
  • 2
1

At start of your script you init $res_users with an empty string ("").

If $_POST['Search'] is not set, you never execute $res_users = mysqli_query( ... );, so $res_users still remains an empty string when you call

if($log_row_users = mysqli_fetch_assoc($res_users))

I suggest you to normalize your code performing all operations concerning queries before HTML output. Otherwise you can repeat the $_POST check:

if(isset($_POST['Search']) && $log_row_users = mysqli_fetch_assoc($res_users))
fusion3k
  • 11,568
  • 4
  • 25
  • 47
1

Fast querying with a more Object orientated method:

[...]
    $sql_users= "SELECT * FROM `users` WHERE `status` LIKE 'Inactive'"; 
    foreach($link->query($sql_users) as $row)
    {
        $status = $row["status"];      
    }
[...]

You can also use it as a boolean to check queries ran:

[...]
    if($db->query($sql)): [...] endif;
[...]

I'd also suggest that you're checking that your result is not null before looping through its data:

[...]
    $result = mysqli_query($link, $sql);
    if($result != null): [...] endif;
[...]

Also, take a look at @fusion3k 's answer. Your infrastructure is causing you limitations. You'll need to re-evaluate how you're approaching this and also check how to prevent SQLi injections.

Edit: You could manage your data flow more simply using an Object-orientated approach (OOP).

class Handler
{
    public function __construct( $args )
    {
         if(is_array( $args ))
         {
             switch($args['type'])
             {
                 case "Insert":
                     break;
                 default:
                     break;
             }
       [...]

Then work with it like so:

new Handler(array(
    'type' => $_POST[...]
    [...] => [...]
));
Community
  • 1
  • 1
Jaquarh
  • 6,493
  • 7
  • 34
  • 86