rosscosack
rosscosack

Reputation: 67

if statement does not evaluate as expected

In the code below, the if statement is evaluated as FALSE where I think it should be TRUE. What am I misunderstanding?

$sql = "SELECT * FROM LIVE";     
$res = mysqli_query($con, $sql);
while ($result = mysqli_fetch_assoc ($res)){
var_dump($result['LIVE']); //string '1' (length=1)
echo $result['LIVE']. "<br>"; //1
}
$a = "1";

if($result['LIVE'] == $a){
echo "It is live!";
}
else {
echo "not live!"; //this gets echoed
}

I have tried all variations of quotes ', ", no quotes

AND changing the data and datatype for the column in the MYSQL table to BIT, CHAR, INT

AND CAST in PHP to BOOL and 'integer'

AND changing the operator eg =, ==, === and have also tried just typing into the if() instead of passing in $a as shown

AND $result = $result['LIVE']; and passing in $result.

I have read PHP type comparison tables and PHP type juggling as well as all the other relative parts of the manual if(), while(), mysqli_fetch_array() etc and can't solve this myself.

I am still learning PHP and I am sure it is an easy fix but I just can't see it.

Upvotes: 0

Views: 80

Answers (4)

user2322215
user2322215

Reputation:

$result = "";

$sql = "SELECT * FROM LIVE";     
$res = mysqli_query($con, $sql);`
while ($result = mysqli_fetch_assoc ($res)){
$result = $result['LIVE'];
echo $result['LIVE']. "<br>"; //1
}
$a = "1";

if($result == $a){
echo "It is live!";
}
else {
echo "not live!"; //this gets echoed
}

Upvotes: 0

JPR
JPR

Reputation: 869

The while loop will repeat and set $result to the value of mysqli_fetch_assoc() each time through the loop. When there are no more results in mysqli_fetch_assoc(), it returns false. Therefore your $result === false at the point you try to evaluate it. Echoing out false in PHP outputs nothing. Echoing !false outputs 1.

Upvotes: 0

Kneel-Before-ZOD
Kneel-Before-ZOD

Reputation: 4221

The while statement exits because $result became false. So, by the time you call $result["live"], it has already become false.

You can simply verify by issuing


var_dump($result);

right before the conditional statement.

To ensure that $a = 1, you must issue that statement inside the loop.
That will resolve your issue.

Hope this explanation is clear and this helps.

Upvotes: 1

DevZer0
DevZer0

Reputation: 13525

your not saving the value of $result; during the final iteration of while loop $result will be set to false because there are no more rows to traverse. which is also what triggers to exit the while loop.

you need to set your value to another temp variable.

while ($result = mysqli_fetch_assoc ($res)){
$temp = $result['LIVE']; //1
}
$a = "1";

if($temp == $a){

Upvotes: 1

Related Questions