hellomello
hellomello

Reputation: 8597

Using PDO fetch to get an array and using if statement

My array would only get a 0 or a 1. I'm using PDO statement for mysql, and this is what I have

$result = $fetching -> fetch();
$first_result = $result[0];

if($first_result === 0){
//do something...
}else{
echo "testing";
}

I'm always getting the testing no matter what, if its 0 or not. I've echoed out the $first_result[0] for testing purposes and it will tell me what the value is. So I know that the value will shoot out either 0 or not 0. But when it is 0, it still echos out testing.

Help please?

Thank you!

Upvotes: 0

Views: 289

Answers (3)

Chathuranga Chandrasekara
Chathuranga Chandrasekara

Reputation: 20956

Seems your types are not matching. === matches value and type

PHP’s === Operator enables you to compare or test variables for both equality and type. Refer below for example.

Read More...

Upvotes: 0

Steven
Steven

Reputation: 1117

The === is testing for type, pdo will return a string in that case so you are testing an int against a string.

Try:

if($first_result === '0'){

Upvotes: 0

devdRew
devdRew

Reputation: 4581

First of all try to put == not type equivalence. And Second I always use this to check if there any record:

$q = $pdo->prepare('Your SQL');
$result = $q->execute($params);
$rows = $q->fetchAll(PDO::FETCH_ASSOC);
if (!count($rows) || !$result)
{
    echo 'No rows or error';
    // To output error $pdo->errorInfo();
}
else
{
    $el = $row[0];
}

Hope that helps.

Upvotes: 3

Related Questions