PHP !is_resource($RS) vs ($RS === false) vs !$RS - php

When checking for a valid resource in PHP, I'm wondering if these are interchangeable. The first two methods are being used where I work and as far as I can tell they are accomplishing the same thing.
Edit: When I first asked this question I was using some code copied from the PHP manual for my example, which contained mysql commands. Since I'm not using mysql I decided it would be better to rewrite the question.
Method 1 - use !is_resource, which has a little more overhead than a direct comparison such as in method 2
$RS = sqlsrv_query($con, $SQL);
if (!is_resource($RS)) {
die('not a resource');
}
Method 2 - a direct comparison
$RS = sqlsrv_query($con, $SQL);
if ($RS === false) {
die('not a resource');
}
Method 3 - is this the same as method 2, just less wordy? Or is there some nuance with the === that I'm missing?
$RS = sqlsrv_query($con, $SQL);
if (!$RS) {
die('not a resource');
}
Thanks

mysql_connect will only return either a resource, or false.
Effectively, !$db_link and $db_link === false are the same. Edit: "in this instance." They aren't actually the same, as === performs strict type checking, but for the purposes of this discussion, they are effectively the same.
is_resource is effectively the same as well, just slightly more overhead but not enough to be concerned for such a micro-optimization.
You should not be writing new code using mysql_ functions. It has been deprecated for a very long time. The replacement was mysqli_.

If you know what possible values you're dealing with, and these values can clearly be distinguished by a simple boolean test, then that is perfectly fine enough. mysql_connect returns either a resource or a boolean false. The boolean false will always be falsey and the resource will always be truthy, hence if (!$db_link) is a perfectly adequate and concise test. There is no case in which this would fail given the two possible values that $db_link can be here.
=== false is more explicit about the boolean comparison, but unnecessarily so. It doesn't add anything, except verbosity.
is_resource also works for your purpose and is more explicit the other way, but again unnecessarily so. It won't match any additional case a simple boolean comparison wouldn't here.

Related

PHP: Error handling with include

$file= #fopen("ssssss.php", r) or die("not found");
(#include("ssssss.php")) or die("not found");
In the first statement we don't put ( ) around #fopen and it is working fine.
But in the second if I didn't put these () it does't show any message.
so why with include I must round it with ( ) ?
I agree with the suggestions in the other answers but the actual answer to your question is this:
In the PHP documentation they say to take care when comparing the return value of include.
That's because it is a special construct and parentheses are not needed.
So when you do this (without wrapping parentheses):
#include("ssssss.php") or die("not found");
You're actually doing this, because or is evaluated first:
#include (("ssssss.php") or die("not found"));
Now, "ssssss.php" is a non empty string that evaluates logically to true.
or is a logical operator that gives true if any of the parameters is true (or both of them).
Also, this operator is short-circuit: if the first parameter is true, php already knows that the operator or will return true, so it doesn't waste time evaluating the second parameter, and die() is not executed.
So finally, or gives true and your sentence becames this:
#include (1);
Php tries to "include 1", and it would raise a warning but it does not because of the #.
Here you have a similar example in php.net.
Your first sentence is not the same case.
$file= #fopen("ssssss.php", r) or die("not found");
fopen is just a regular Php's function with its parentheses. Here you need to have in mind two operators: = and or.
= has higher precedence than or, so, if fopen's result is correctly assigned to $file (and it is), that operation will return true. And, as I explained before, "true or anything else", gives true but die() is not executed because of the short-circuit operator.
You should be using file_exists instead of using the # as the later covers all sorts of issues. A better solution would be...
if (file_exists("ssssss.php")) {
$file= #fopen("ssssss.php", r);
}
and
if (file_exists("ssssss.php")) {
include("ssssss.php");
}
That's not really a good use of include. If you need to include a php file and generate an error on failure, use require or require_once.
If you need to get the contents of the whole file, you could use file_get_contents().
Also, I agree with Nigel Ren about the use of # - it is a dangerous practice and should be avoided.

What does "or" do in the context of errors?

Reading this question I want to copy #Your Common Sense's error checking when using mysqli
$query="INSERT INTO testtable VALUES (23,44,56)";
$stmt_test->prepare($query);
$stmt_test->execute() or trigger_error($stmt_test->error);
$stmt_test->close();
How does or work? Another example of it's use is
$fh = fopen($myFile, 'w') or die("can't open file");
How is it different than using an if statment and would should it be used instead?
If the first statement returns false, then the second one is executed. That's it.
This is often how boolean "or" expressions are evaluated in programming languages. If you have a statement involving functions thus:
if (a() or b()) { ... }
then PHP works out that, if a() returns true, there is no need to evaluate the second function, since the overall result will be true regardless of the outcome of the second part. We can use this trick as a simple if mechanism:
(operation_that_might_fail() or report_error());
Here, I've removed the if around the clause. This will be evaluated just as before - except the result of ORing the two is then thrown away, since we don't need to do anything with it.
For this to work, operation_that_might_fail() must return boolean true on success, and false otherwise. As it happens, many PHP functions do exactly that, so we can often use this approach.
Side note: whilst the statement or is arguably clearer, PHP programmers tend to prefer the operator ||. Similarly, and will do what it says, but && is more common.

Which method I should use and why?

I am establishing a database connection in php using the function
$DBConn = mysql_connect ("localhost" , "testuser" , "test123")
At the time of releasing the connection I am using
if( is_resource($DBConn) )
to check whether the connection is currently set or not. I want to know is it efficient to do this or I should check the connection like this
if( $DBConn )
I want to know prod and cons of using both the statements.
First of all, you should no longer be using mysql_xxx functions; there are many articles out there that discuss the benefits of having prepared statements, etc. with PDO / mysqli.
By looking at the manual, it states that it returns a link identifier or false on failure. You shouldn't make assumptions as to what exactly this identifier is, it's usually a resource but it may as well be an object or integer. I would simply negate the easier condition:
if (false !== $DBConn) {
// do something with the database
}
Or, alternatively:
if (false === $DBConn) {
throw new Exception("Could not connect to database");
}
// do something with the database
Edit
Using if ($DBConn) { ... } is okay as well, because it's basically the opposite of 0, false, null, "" and empty array.
Both of them are essentially the same, though one might argue that called the is_resource method has the overhead of calling the function, the if also has to determine this and it virtually leaves no difference between both of them. Its all about your style of coding and readability i guess
A resource identifier is returned upon successful connection or querying. Thus the function is_resource will identify a variable as a resource or false.
and if an If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE, it won't.

PHP generating a phantom warning for code that is not executed

In an effort to tidy up my code, I've encapsulated my database reads into its own function, which accepts a SQL command for the argument, as well as an optional $getArray argument which specifies whether I am returning an array as the result (true for SELECT, false for UPDATE, etc).
function readDB($sql, $getArray = false)
{
$conn = odbc_connect('myAccessDataBase', '', '');
if (!$conn)
return exit('Connection Failed: '.$conn);
if ($getArray = false)
odbc_exec($conn, $sql);
else
{
$res = odbc_exec($conn, $sql);
if (!$res)
return exit('Error in SQL');
return odbc_fetch_array($res);
}
odbc_close($conn);
}
The code above works as expected except for one small caveat. If I am performing an UPDATE vs a SELECT, I get a warning due to $getArray being set to false:
Warning: odbc_fetch_array() [function.odbc-fetch-array]: No tuples available at this result index in C:...\functions.php on line 14
I understand the warning, which makes sense if that line were to actually be executed, however it is not. My question is in regards as to why PHP is evaluating the contents of the else portion of my if statement, which is not even being hit during runtime. I understand that the UPDATE cannot return an array, hence why I am evaluating $getArray to determine whether I expect such a return. What can I do to circumvent this warning? Regardless, I am still pretty fresh with my PHP, and am probably going about this the wrong way anyhow. Cheers!
You're setting the variable TO FALSE instead of evaluating it FOR FALSE If you change this line:
if ($getArray = false)
to
if ($getArray == false)
It should work.
edit
On another note, you should do your test in reverse. Instead of testing for false, test for true and THEN have an else. It makes a little more sense logically for anyone coming in to look at your code later.
Instead of If this IS NOT the case then do this it makes more sense to say if this is the case, do this
So switch your code blocks around and test:
if ($getArray)
The line
if ($getArray = false)
must be
if ($getArray == false)

identity conditional "===" , performance, and conversion

I've always came away from stackoverflow answers and any reading I've done that "===" is superior to "==" because uses a more strict comparison, and you do not waste resources converting value types in order to check for a match.
I may be coming at this with the wrong assumption, so I assume part of this question is, "is my assumption true?"
Secondly,
I'm dealing specifically with a situation where I'm getting data from a database in the form of a string "100".
The code I am comparing is this...
if ($this->the_user->group == 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
vs.
if ( (int) $this->the_user->group === 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
or even
if (intval($this->the_user->group) === 100) //admin
{
Response::redirect('admin/home');
}
else // other
{
Response::redirect('user/home');
}
is any integrity (or performance) gained by manually casting or converting simply so you can use the identity ('===') comparison?
In your particular case == is the better option. As you (as can be seen in your code) have probably already found out many database functions will always return strings, even if you fetch an integer. So type strict comparison really only bloats your code.
Furthermore you are adding a potential (let's call it theoretic) security risk. E.g. (int) '100AB2' would yield 100. In your case this probably can't happen, but in others it may.
So: Don't overuse strict comparison, it's not always good. You mainly need it only in ambiguous cases, like the return value of strpos.
There is a performance difference between == and === - latter will be even twice as fast, see Equal vs identical comparison operator.
The difference, however is too small to be bothered with - unless the code is executed millions of times.
That's a really tiny optimization you're doing there. Personally, I don't think it's really worth it.
Any boost you gain from not casting the value when using === is lost when you explicitly cast the value. In your case, since the type is not important to you, you should just do == and be done with it.
My recommendation would be to keep === for when you need to check type as well - e.g. 0 evaluating to false and so on.
Any performance gains will be microscopically small, unless you're performing literally billions and trillions of these comparisons for days/months/years on-end. The strict comparison does have its uses, but it also is somewhat of anomally in PHP. PHP's a weakly typed language, and (usually) does the right thing for auto-converting/casting values to be the right thing. Most times, it's not necessary to do a strict comparison, as PHP will do the right thing.
But there are cases, such as when using strpos, where the auto-conversion will fail. strpos will return '0' if the needle you're searching is right at the start of the haystack, which would get treated as FALSE, which is wrong. The only way to handle this is via the strict comparison.
PHP has some WTF loose comparisons that return TRUE like:
array() == NULL
0 == 'Non-numeric string'
Always use strict comparison between a variable and a string
$var === 'string'

Categories