开发者

Simple Issue with PHP While Loop

开发者 https://www.devze.com 2023-02-07 05:24 出处:网络
I have this mysqli_select_db($connect,\"users\"); $response开发者_运维知识库 = \"Select * from revbut where onuser=\'$u\'\";

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?


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.


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++;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消