I'm writing a php app to access a MySQL database, and on a tutorial, it says something of the form
mysql_connect($host, $user, $pass) or die("could not connect");
How does PHP know that the function failed so that it runs the die part? I guess I'm asking how the "or" part of it works. I don't think I've seen it before.
If the first statement returns true, then the entire statement must be true therefore the second part is never executed.
For example:
$x = 5;
true or $x++;
echo $x; // 5
false or $x++;
echo $x; // 6
Therefore, if your query is unsuccessful, it will evaluate the die() statement and end the script.
PHP's or works like C's || (which incidentally is also supported by PHP - or just looks nicer and has different operator precedence - see this page).
It's known as a short-circuit operator because it will skip any evaluations once it has enough information to decide the final value.
In your example, if mysql_connect() returns TRUE, then PHP already knows that the whole statement will evaluate to TRUE no matter what die() evalutes to, and hence die() isn't evaluated.
If mysql_connect() returns FALSE, PHP doesn't know whether the whole statement will evaluate to TRUE or FALSE so it goes on and tries to evalute die() - ending the script in the process.
It's just a nice trick that takes advantage of the way or works.
It works as others have described.
In PHP, do not use "die", as it does NOT raise an exception (as it does in Perl). Instead throw an exception properly in the normal way.
die cannot be caught in PHP, and does not log - instead it prints the message ungracefully and immediately quits the script without telling anybody anything or giving you any opportunity to record the event, retry etc.
If you would like to add more code if the connection doesn't work, beyond a die statement:
$con=mysql_connect($host, $user, $pass)
if(!$con)
{
// ... add extra error handling code here
die("could not connect");
}
else
{
echo "Connected";
}
Related
If I use a bit of code like this:
$update_result = mysqli_query( $link , $sql_update_login ) or die ('Unable to execute query. '. mysqli_error($link));
Does it have to die or can you put a different query afterwards? Like a predetermined function that writes a log of the error to another table? Such as:
$update_result = mysqli_query( $link , $sql_update_login ) or function('$query, $error);
What are the other options after 'or'? I haven't found it in the documentation, any clues are appreciated.
Does it have to die
Quite contrary, it shouldn't or die() ever.
PHP is a language of bad heredity. Very bad heredity. And or die() with error message is one of the worst rudiments:
die throws the error message out, revealing some system internals to the potential attacker
such error message confuses casual users, because they don't understand what does it mean
Besides, die kills the script in the middle, leaving users without familiar interface to work with, so they'd likely just drop out
it kills the script irrecoverably. While exceptions can be caught and gracefully handled
die() gives you no hint of where the error has been occurred. And in a relatively big application it will be quite a pain to find.
So, never use die() with MySQL errors, even for the temporary debugging: there are better ways.
Instead of manually checking for the error, just configure mysqli to throw exceptions on error, by adding the following line to your connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and after that just write every mysqli command as is, without any or die or anything else:
$result = mysqli_query($link, $sql);
This code will throw an exception in case of error and thus you will always be informed of every problem without a single line of extra code.
A more detailed explanation on how to make your error reporting production ready, uniform and overall sensible while making your code much cleaner, you can find in my article on PHP error reporting.
or is just an operator (very similar to ||).
The or die() syntax works because or short-circuits, which means that if the first statement is true, True or X will always be true, so X isn't evaluated and your script doesn't die.
Yes, you can provide a different function after the (or).
I have tested the following:
mysqli_query($sel_db,'what!') or some_func(mysqli_error($sel_db));
function some_func($str) {
die("ERROR: ".$str);
}
It doesn't have to be die() specifically, but it needs to be something that'll make the script halt by calling exit() or die(), or something that throws an exception. Otherwise, the script will continue with the return value of that function (which is probably either null or some sort of junk) in $update_result, which will almost certainly cause problems.
If I use a bit of code like this:
$update_result = mysqli_query( $link , $sql_update_login ) or die ('Unable to execute query. '. mysqli_error($link));
Does it have to die or can you put a different query afterwards? Like a predetermined function that writes a log of the error to another table? Such as:
$update_result = mysqli_query( $link , $sql_update_login ) or function('$query, $error);
What are the other options after 'or'? I haven't found it in the documentation, any clues are appreciated.
Does it have to die
Quite contrary, it shouldn't or die() ever.
PHP is a language of bad heredity. Very bad heredity. And or die() with error message is one of the worst rudiments:
die throws the error message out, revealing some system internals to the potential attacker
such error message confuses casual users, because they don't understand what does it mean
Besides, die kills the script in the middle, leaving users without familiar interface to work with, so they'd likely just drop out
it kills the script irrecoverably. While exceptions can be caught and gracefully handled
die() gives you no hint of where the error has been occurred. And in a relatively big application it will be quite a pain to find.
So, never use die() with MySQL errors, even for the temporary debugging: there are better ways.
Instead of manually checking for the error, just configure mysqli to throw exceptions on error, by adding the following line to your connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and after that just write every mysqli command as is, without any or die or anything else:
$result = mysqli_query($link, $sql);
This code will throw an exception in case of error and thus you will always be informed of every problem without a single line of extra code.
A more detailed explanation on how to make your error reporting production ready, uniform and overall sensible while making your code much cleaner, you can find in my article on PHP error reporting.
or is just an operator (very similar to ||).
The or die() syntax works because or short-circuits, which means that if the first statement is true, True or X will always be true, so X isn't evaluated and your script doesn't die.
Yes, you can provide a different function after the (or).
I have tested the following:
mysqli_query($sel_db,'what!') or some_func(mysqli_error($sel_db));
function some_func($str) {
die("ERROR: ".$str);
}
It doesn't have to be die() specifically, but it needs to be something that'll make the script halt by calling exit() or die(), or something that throws an exception. Otherwise, the script will continue with the return value of that function (which is probably either null or some sort of junk) in $update_result, which will almost certainly cause problems.
If I use a bit of code like this:
$update_result = mysqli_query( $link , $sql_update_login ) or die ('Unable to execute query. '. mysqli_error($link));
Does it have to die or can you put a different query afterwards? Like a predetermined function that writes a log of the error to another table? Such as:
$update_result = mysqli_query( $link , $sql_update_login ) or function('$query, $error);
What are the other options after 'or'? I haven't found it in the documentation, any clues are appreciated.
Does it have to die
Quite contrary, it shouldn't or die() ever.
PHP is a language of bad heredity. Very bad heredity. And or die() with error message is one of the worst rudiments:
die throws the error message out, revealing some system internals to the potential attacker
such error message confuses casual users, because they don't understand what does it mean
Besides, die kills the script in the middle, leaving users without familiar interface to work with, so they'd likely just drop out
it kills the script irrecoverably. While exceptions can be caught and gracefully handled
die() gives you no hint of where the error has been occurred. And in a relatively big application it will be quite a pain to find.
So, never use die() with MySQL errors, even for the temporary debugging: there are better ways.
Instead of manually checking for the error, just configure mysqli to throw exceptions on error, by adding the following line to your connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and after that just write every mysqli command as is, without any or die or anything else:
$result = mysqli_query($link, $sql);
This code will throw an exception in case of error and thus you will always be informed of every problem without a single line of extra code.
A more detailed explanation on how to make your error reporting production ready, uniform and overall sensible while making your code much cleaner, you can find in my article on PHP error reporting.
or is just an operator (very similar to ||).
The or die() syntax works because or short-circuits, which means that if the first statement is true, True or X will always be true, so X isn't evaluated and your script doesn't die.
Yes, you can provide a different function after the (or).
I have tested the following:
mysqli_query($sel_db,'what!') or some_func(mysqli_error($sel_db));
function some_func($str) {
die("ERROR: ".$str);
}
It doesn't have to be die() specifically, but it needs to be something that'll make the script halt by calling exit() or die(), or something that throws an exception. Otherwise, the script will continue with the return value of that function (which is probably either null or some sort of junk) in $update_result, which will almost certainly cause problems.
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.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP - and / or keywords
I saw several bits of PHP code using or in a way I was unfamiliar with. For example:
fopen($site,"r") or die("Unable to connect to $site");
Is this equal to this ||?
Why would you use this instead of a try catch block? What will cause the program run the or die()?
It is for the most part, but...
The reason for the two different
variations of "and" and "or" operators
is that they operate at different
precedences.
See http://php.net/manual/en/language.operators.logical.php
or is equal to || except that || has a higher presedense than or.
Reference:
http://www.php.net/manual/en/language.operators.precedence.php
or has an other precedence. The concrete statement is little trick with boolean operators. Like in a common if-test-expression the second part is only executed, if the first is evaluated to false. This means, if fopen() does not fail, die() is not touched at all.
However, try-catch only works with Exceptions, but fopen() doesnt throw any.
Today something like this is "not so good" style. Use exceptions instead of hard abortion
if (!($res = fopen($site, 'r'))) throw new Exception ("Reading of $site failed");
or die happens with the first command fails.
It is similar to a try catch, but this is more direct approach.
Note that this is a classical test:
fopen($site,"r") or die("Unable to connect to $site");
Only if fopen($site,"r") returns false, will the second half of the test be run: 'die('error')'.
Same is if(a || b); b is only run if a returns false.
Die in PHP is the same as exit();
http://www.php.net/manual/en/function.exit.php
Stops execution of the current script entirely, and prints out the error message.
Yes it equals ||
In this case it is explicitly stopping the execution of the page and printing that error message.