Extreme Dimension Extreme Dimension - 6 months ago 24
SQL Question

How to retain the mysqli_fetch_array() value in while loop?

I don't know if the question is clear enough in the title.

I'm fetching some IDs from table A and the query returns multiple rows. I'm also fetching some other IDs from other table B.My question is I want to check if the ID of table A is same as of ID in table B, and if so I have to print a value else other value should be printed.How can I do this?

I have tried using two while loops (one inside the other) but the inner while loop executes only one time and the value becomes null. So its unable to check the condition.

<?php
include('includes/template.php');
$user=$_SESSION['login_user'];

if(isset($_POST['action'])){
if($_POST['action']=="searchb"){
$query=secure_input($_POST['searchbox']);
if(!empty($query)){
$sql="select id,username, name, email from mysql.registration_zany where name like '%".$query."' and privacy=0";
$res=mysqli_query($con,$sql);
$resmsg="<div class='alert alert-success' role='alert'>SEARCH RESULTS FOR :<b>".$query."</b></div>";
}
}
}
$sql2="select id from mysql.friends where id2='".$id."' and Request_Status=1 and id !=".$id;
$res2=mysqli_query($con,$sql2);
$i=1;
while($row=mysqli_fetch_array($res,MYSQLI_NUM)){
$flag=0;
while($fr[i]=mysqli_fetch_array($res2,MYSQLI_NUM)){
#echo $row[0];
if($fr[i][0]==$row[0]){
$flag=1;
}
}
$i++;
if($flag){
$table="<div class='row'>
<div class='col-xs-6 col-md-4'>
<div class='thumbnail'>
UserName:".$row[1]."<br>Profile:".$row[2]."<br>E-mail:".$row[3]."
<p><span class='label label-info'>Friend</span></p></div></div>";
echo $table;
}
else{
$table="<div class='row'>
<div class='col-xs-6 col-md-4'>
<div class='thumbnail'>
UserName:".$row[1]."<br>Profile:".$row[2]."<br>E-mail:".$row[3]."
<p><form action='request.php' method='post'>
<input name='action' type='hidden' value='".$row[0]."' >
<input type='submit' class='btn btn-primary' name='req' value='Send Request'>
</form></p></div></div>";
echo $table;
}
}
?>


Thank you.

PSN PSN
Answer

The inner while loop becomes null and so its not checking the if condition inside it.

My suggestion is to use mysqli_free_result(); and after that execute the sql statement outside the inner while loop.

mysqli_free_result($res2);
$sql2="select id from mysql.friends where id2='".$id."' and Request_Status=1  and id !=".$id;
$res2=mysqli_query($con,$sql2);

Hope this helped you.

Comments