sarthak
sarthak

Reputation: 297

Simple Issue with PHP While Loop

I have this

mysqli_select_db($connect,"users");

$response = "Select * from revbut where onuser='$u'";
$rquery  =  mysqli_query($connect,$response);
$norows = mysqli_num_rows($rquery);






while($responseanswer=mysqli_fetch_array($rquery)){


if(json_encode($responseanswer['response']=='approve'))
{
include('response-2.php');  
}

else if(json_encode($responseanswer['response']=='reject'))
{
    include('response-3.php');
}
else
{
echo "Nothing in here. ";   
}
}

in database, there are two fields. So one is approve, whereas the other is reject. But the php is including the response-2.php file twice. why so?

Upvotes: 1

Views: 208

Answers (3)

technoTarek
technoTarek

Reputation: 3228

Because you're running the loop for every record in your result set. Your loop basically says include response-2.php every time the 'response' field equals "approve". If you have 5 records in the table where the 'response' field is "approve", your loop will include response-2.php 5 times.

Before your while loop, you could establish an iteration variable:

$i = 1;

At the end of your loop, iterate the value by one:

$i++;

Then, check the value of $i. If it equals anything greater than 1, don't do the include again. For example:

$i = 1;
while($responseanswer=mysqli_fetch_array($rquery)){


if(json_encode($responseanswer['response']=='approve'))
{
($i == 1 ? include('response-2.php') : "");  
}

else if(json_encode($responseanswer['response']=='reject'))
{
($i == 1 ? include('response-3.php') : "");  
}
else
{
echo "Nothing in here. ";   
}
$i++;
}

Upvotes: 1

AmirModiri
AmirModiri

Reputation: 775

i think you must do this in you database and you should do this:

have one record that hase key column and value the key name is for example

rejectOrAprove and the value if its aprove be 1 and if reject be 0.

Upvotes: 0

Ben XO
Ben XO

Reputation: 1219

Because you are comparing $responseanswer['response'] with 'approve' and with 'reject', and then json_encoding() the true or false. The json encoding will be a string such as "true" or "false", and if("true") and if("false") in PHP are both true. In fact, the only strings that will if() to false are the strings "0" and "". It even specifically mentions if("false") here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

It's not clear why the json_encoding() is needed at all, because you haven't given any sample data, but I'm pretty sure that's the bug.

Upvotes: 3

Related Questions