PHP MySQL comparison always true regardless of operands and operator - php

For the record, I read documentation on boolean comparisons in PHP, but I do not understand how my code relates in this context. I thought I had a problem connecting to MySQL, but it turns out everything is fine and I can make queries without issue. So, MySQL is not really that relevant to this post.
I use this to report errors in an object that tried to connect on construction. Note that I tried ==, ===, != and !== only to get the same problem. I even tried casting the argument to bool and boolean.
Comments in below code blocks are relevant.
private function assert($test){ // Tried renaming in case PHP was funny about it.
if ($test === FALSE){ // Tried ==, ===, !== and != and casting $test.
if ($this->use_exception){
throw new mysql_exception();
}else{
die("MySQL ".mysql_errno()." - ".mysql_error());
}
}
}
Connecting is typical.
$this->con = mysql_connect($host, $un, $pw, false, $ssl ? MYSQL_CLIENT_SSL : 0);
// I get 'yay'
echo mysql_ping($this->con) ? "yay" : "nay";
// This disagrees. Tried no cast, and a cast to bool.
$this->assert((boolean)($this->con != FALSE));
mysql_ping() says everything is ok, but assert() stops the presses no matter what.
I tried every operator and cast combination, even renaming the function out of paranoia over a name clash. Why does assert() only see true?
EDIT:
To make my problem clearer, consider the alternative implementation with Eugen's suggested use of is_resource. The problem is that I just have no idea why the below happens.
private function assert($test){
$test = $test ? true : false;
if ($test === FALSE){
echo "$test === false<br />";
}
if ($test == FALSE){
echo "$test == false<br />";
}
if ($test !== FALSE){
echo "$test !== false<br />";
}
if ($test == FALSE){
echo "$test != false<br />";
}
}
Output is out of order and the value changed after one comparison. Since I can make queries, $test must be true. I should not get output at all, but I do for every operator. I also tried it with FALSE replaced by 0.
Bad PHP instance?
1 !== false
=== false
!== false
!= false

$this->assert(is_resource($this->con));

can't you use your second example and combine the function? you already get a value (yay/nay)
$this->con = mysql_connect($host, $un, $pw, false, $ssl ? MYSQL_CLIENT_SSL : 0);
$this->assert = mysql_ping($this->con) ? 1 : 0;
just thinking out loud

Related

The best way to check the conditions

The best way to check the conditions and what is difference between them?
This is my usual way:
if ($this->_is_valid_number() == TRUE) {
//do some thing...
}
I've seen some code written in this way(for example):
if (TRUE == $this->_is_valid_number()) {
//do some thing...
}
Are these different from each other? Which method is standard?
None of the above, really.
== true is redundant with if(condition) so it could just be written as if ($this->_is_valid_number()) which is pretty standard. If you want to check for false, you would do if (!$this->_is_valid_number()) and if you would check for any other condition, you usually write like you would speak:
If my number is not one -> if($number !== 1)
Notice: Also check this article for difference between == and === operators
The second method has a added benefit of failing if it's used incorrect.
The second one sets true to $number and creates no error, which is what the code should do but not what the coder is expecting.
Do it the other way around and it will fail
$number =5;
if($number == true) echo "true"; // true
if($number = true) echo "true"; //true
if(true == $number) echo "true"; // true
if(true = $number) echo "true"; // fails
https://3v4l.org/suF9s

PHP operators (! $a vs. false === $a)

What is the difference, specifically in PHP? Logically they're the same (or so seem), but is there any advantage with one over the other? Including micro-benchmarking if any difference.
Example code:
$a = fc();
// Example 1
if (!$a) echo "Ex. 1";
// Example 2
if (false === $a) echo "Ex. 2";
// Example 3
if (true !== $a) echo "Ex. 3";
function fc()
{
return false;
}
!
Just invert your result value (boolean or not) from true to false or false to true
Example:
if (!file_exists('/path/file.jpg')) {
// if file NOT exists
}
=== false (or true)
The value compared MUST BE a boolean false or true.
Example:
$name = 'Patrick Maciel';
if ($name === true) {
// not is, because "Patrick Maciel" is a String
}
BUT if you do that
if ($name == true) {
// it is! Because $name is not null
// and the value is not 'false': $name = false;
}
In this case, this operator is just for check that:
$connection = $this->database_connection_up();
if ($connection === true) {
echo 'connected to database';
} else {
echo 'error in connection';
}
$valid_credit_card = $this->validate_credit_card($information);
if ($valid_credit_card === false) {
echo 'Your credit card information is invalid'
}
!== true (or false)
It's the same thing. Only the opposite of ===, ie: the value cannot be a boolean true or false.
Sorry for my english.
The difference boils down to type juggling. The ! operator converts a value to its boolean value, then inverts that value. === false simply checks if the value is, in fact, false. If it's not false, the comparison will be false.
If the value being compared is guaranteed to be a boolean, these operations will behave identically. If the value being compared could be a non-boolean, the operations are very much different. Compare:
php > $a="0";
php > var_dump(!$a);
bool(true)
php > var_dump($a === false);
bool(false)
php > $a = false;
php > var_dump(!$a);
bool(true)
php > var_dump($a === false);
bool(true)

The best practice for not null if statements

I've been writing my "If this variable is not empty" statements like so:
if ($var != '') {
// Yup
}
But I've asked if this is correct, it hasn't caused a problem for me. Here is the answer I found online:
if (!($error == NULL)) {
/// Yup
}
This actually looks longer than my approach, but is it better? If so, why?
Rather than:
if (!($error == NULL))
Simply do:
if ($error)
One would think that the first is more clear, but it's actually more misleading. Here's why:
$error = null;
if (!($error == NULL)) {
echo 'not null';
}
This works as expected. However, the next five values will have the same and (to many, unexpected) behavior:
$error = 0;
$error = array();
$error = false;
$error = '';
$error = 0.0;
The second conditional if ($error) makes it more clear that type casting is involved.
If the programmer wanted to require that the value actually be NULL, he should have used a strict comparison, i.e., if ($error !== NULL)
It is good to know exactly what is in your variable, especially if you are checking for uninitialized vs null or na vs true or false vs empty or 0.
Therefore, as mentioned by webbiedave, if checking for null, use
$error !== null
$error === null
is_null($error)
if checking for initilized, as shibly said
isset($var)
if checking for true or false, or 0, or empty string
$var === true
$var === 0
$var === ""
I only use empty for ''s and nulls since string functions tend to be inconsistent. If checking for empty
empty($var)
$var // in a boolean context
// This does the same as above, but is less clear because you are
// casting to false, which has the same values has empty, but perhaps
// may not one day. It is also easier to search for bugs where you
// meant to use ===
$var == false
If semantically uninitialized is the same as one of the values above, then initialize the variable at the beginning to that value.
$var = ''
... //some code
if ($var === '') blah blah.
Why just don't
if (!$var)
There are ways:
<?php
error_reporting(E_ALL);
$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));
?>
Another:
<?php
$var = '';
// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
echo "This var is set so I will print.";
}
?>
To check if it's empty:
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>

Catching hell with if's in php?

ok forgive my technique in writing here, but i can't seem to understand why this code recognizes things and then doesn't recognize some other things.
my code:
if (!isset($id)) {
$_SESSION["logged_in"] = False;
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
if ($_SESSION["logged_in"] = False)
{ echo "session variable is set at False"; }
if ( $_SESSION["logged_in"] = True)
{ echo "session variable is set at True"; }
}
now as I see it, if it enters this bit of code at all, the first thing that happens should be that the variable gets set to "false". elsewhere in some code not shown it gets set to true and that part works fine but when i try to force it into this for a false setting it remains true.. can anyone see why this wouldn't get set to "False" at this point in the execution?
You should be using == for comparison here, not = for assignment:
if ($_SESSION["logged_in"] = False)
// ---------------^^^
// Should be
if ($_SESSION["logged_in"] == False)
// Also here:
if ( $_SESSION["logged_in"] = True)
//--------------------------^^
// Should be
if ($_SESSION["logged_in"] == True)
You are making a classic mistake by assigning the variable in your if statement instead of comparing it. So, change your if statements to:
if ($_SESSION["logged_in"] == false)
Instead of (where you are assigning):
if ($_SESSION["logged_in"] = false)
By the way, you're statement has now some duplication since the variable itself already is true of false. So, there is no need to check it against the boolean. So, this can be enough:
if ($_SESSION["logged_in"]) //equals true if user is logged in
if (!$_SESSION["logged_in"]) // equals true if user is NOT logged in
You need == or ===
Using = means its equal :)
if (!isset($id)) {
$_SESSION["logged_in"] = False;
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
if ($_SESSION["logged_in"] == False)
{ echo "session variable is set at False"; }
if ( $_SESSION["logged_in"] == True)
{ echo "session variable is set at True"; }
}
You should be using the == operator rather than = in your if statements.
EG
if ($_SESSION["logged_in"] == False)

Checking if isset and is true?

Is there a function to check both
if (isset($var) && $var) ?
The empty() function will do the job.
Use it with the not operator (!) to test "if not empty", i.e.
if(!empty($var)){
}
You may use the ?? operator as such:
if($var ?? false){
...
}
What this does is checks if $var is set and keep it's value. If not, the expression evaluates as the second parameter, in this case false but could be use in other ways like:
// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
More info here:
https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator
there you go. that should do it.
if (isset($var) && $var)
if (! empty($var))
It seems as though #phihag and #steveo225 are correct.
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
So, it seems !empty($var) would be the equivalent to isset() && $var == true.
http://us2.php.net/empty
Try the empty function:
http://us2.php.net/empty
isset($a{0})
isset AND len is not 0 seems more reliable to me, if you run the following:
<?php
$a=$_REQUEST['a'];
if (isset($a{0})) { // Returns "It's 0!!" when test.php?a=0
//if (!empty($a)) { // Returns "It's empty!!" when test.php?a=0
echo 'It\'s '.$a;
} else { echo 'It\'s empty'; }
?>
$a = new stdClass;
$a->var_false = false;
$a->var_true = true;
if ($a->notSetVar ?? false) {
echo 'not_set';
}
if ($a->var_true ?? false) {
echo 'var_true';
}
if ($a->var_false ?? false) {
echo 'var_false';
}
This way:
if (($var ?? false) == true) {
}
I am amazed at all these answers. The correct answer is simply 'no, there is no single function for this'.
empty() tests for unset or false. So when you use !empty(), you test for NOT UNSET (set) and NOT FALSE. However, 'not false' is not the same as true. For example, the string 'carrots' is not false:
$var = 'carrots'; if (!empty($var)){print 1;} //prints 1
in fact your current solution also has this type problem
$var = 'carrots'; if (isset($var) && $var){print 1;} //prints 1
as does even this
$var = '1.03'; if (isset($var) && $var == true){print 1;} //prints 1
in fact... if you want to do as you described exactly, you need:
$var = 'carrots'; if (isset($var) && $var === true){print 1;} //Note the 3 Equals //doesn't print 1
I suppose the shortest valid way to test this case is :
if (#$var === true){ print 1;}
But suppressing errors for something like this is pretty awful practice.
Don't know if an exact one already exists, but you could easily write a custom function to handle this.
function isset_and_true($var) {
return (isset($var) && $var == true) ? true : false;
}
if (isset_and_true($a)) {
print "It's set!";
}
Check if the variable is set, and true. Ignore warning message
if(#!empty($foo))

Categories