/    Sign up×
Community /Pin to ProfileBookmark

Checking a variable

Hey,

I have code like this on my site:

[code=php]$conn = sqlsrv_connect($serverName, $connectionInfo);
if($conn === false)
{
echo “Could not connect.n”;
die(print_r(sqlsrv_errors(), true));
}

$tsql = “SELECT fProductRefNum1
FROM fProducts”;

$stmt = sqlsrv_query($conn, $tsql);
if (!$stmt)
{
echo “Error in statement execution.n”;
die(print_r(sqlsrv_errors(), true));
}[/code]

I just want to know which is better (or how they differ):

[B]if (!$stmt)[/B] -or- [B]if($stmt === false)[/B]

Which case should I use and how/why would it matter?

That’s it… thanks!

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiMay 14.2009 — They do not mean the same thing. ! is the same as == false, in that they both check if an expresion evaluates to false. === means than not only does expression have to evaluate to false, it has to be of the type boolean. In practice, the difference is that PHP treats certain values of other types as false, including the integer 0, the float 0.0, a string "0", an empty string "" and an empty array (and others i cant think of off the top of my head probably!).

Sometimes these doesn't logically equate to false in the sense of failure - for example the function strpos() which is used to check the position of a string in another could return 0 indicating that one string is at the start of the other one, and false on error. You need to be able to differentiate between 0 and true boolean false. This is where === comes in.

So, in your case it wont actually matter because sqlsrv_connect returns a resource on success (which does not evaluate to false) or true boolean false. In this case either option will work, but you really need to understand reasons for each because certain other functions will not behave as expected.
Copy linkTweet thisAlerts:
@dtm32236authorMay 14.2009 — That was an absolutely perfect explanation... it answered every question can think of regarding 'false' and '===' vs '=='

Thanks a lot Mindzai.
×

Success!

Help @dtm32236 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...