Php connexion mysql or die

mysqli or die, does it have to die?

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.

Sure you can call a function after the or (it is an operator, as Blender says below). Defining one as you appear to be doing, though, isn’t really possible or meaningful.

4 Answers 4

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.

Источник

How does «do something OR DIE()» work in PHP?

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.

Читайте также:  HTML Headings

As an aside, don’t use this kind of logic in actual applications. It still amazes me how many tutorials do that.

Is might be simple and appropriate for a tutorial, but you do not want your script to die ungracefully with an error message like that in front of real users. Showing a custom error page (without specifying the actual error!) + logging the error is a must.

4 Answers 4

If the first statement returns true , then the entire statement must be true therefore the second part is never executed.

$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.

Good explanation. This «implied if» language construct of PHP is a little dangerous, because you can have statements that you think get executed but really don’t, and that’s not as obvious as if you had an if block.

By the way, you can only use a single statement after OR. A block statement will fail syntax checking (e.g. actual error message could be Parse error: syntax error, unexpected ‘

And here I was, thinking this was some kind of advanced feature like python’s with statement, when it’s actually just a boolean expression. I think extra care should be taken when using this expression if you’re expected to perform a cleanup in case of errors. Please, correct me if I’m wrong, but if you do func_call($file) or die(); and the function fails, then the file is left open when the scripts dies.

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.

Читайте также:  Узнать html код символа

It’s just a nice trick that takes advantage of the way or works.

Источник

die() or try/catch when interacting with MySql database in PHP?

A lot of tutorials and books I have been over and read have used the die() method to catch an exception when interacting with a local MySQL database For example:

mysql_connect($dbhost, $dbuser, $dbpass)or die(mysql_error()); 

Would a try/catch block be more beneficial over the die() method or is that just the standard way that exception handling works with db connections?

try/catch allows you to handle Exceptions cleanly, whereas die() is abrupt and rarely allows you to display user-friendly messages. but mysql_connect doesn’t throw any Exception, and the MySQL_* functiond are deprecated and won’t exist in PHP for much longer

No, you can write your way to handle this exception as you like (stackoverflow.com/a/9836727/3615630)

use die in development. How would you like die if you were booking a flight on Travelocity ? Also, why in the world are you using mysql_* functions? It is the 21st century :>

Correction: a lot of bad tutorials and books use die() . It’s not the job of the code that connects to the database to decide when the application ends or how it reacts when the database is not accessible. Forget about die() , you don’t need it. The place where the function exit() (the real name of die() ) is needed is just after header(‘Location:’); if you don’t use a framework and handle these things manually. Apart from that, the usage of exit() is a code smell.

2 Answers 2

or die() is an extremely primitive way to «handle» errors and only for examples or debugging at best. In practice, it depends on how you handle your errors. You may want to return false from a function call or you may want to throw your own exception instead; e.g.:

try..catch will do exactly nothing with mysql , since mysql never throws any exceptions. It only ever returns false on failure.

You will have to have your own error handling strategy. You’ll probably want to log errors and display a user friendly error page instead of cryptic error messages. mysql is not concerned with that part. It only gives you a way to check whether an operation was successful or not (check if it returns false ); what you do with this information is up to you. die kills the entire application and at least doesn’t allow the problem to propagate further; but it certainly does not display any user friendly error pages.

Читайте также:  Html select onclick value

Having said all this, mysql is old and deprecated. If you’d use something newer like PDO instead, it can properly throw exceptions itself.

Источник

Check for database connection, otherwise display message

I would like to check if the website can connect to mySQL. If not, I would like to display an error saying that the user should try to access the page again in a few minutes. I really do not know how to do this 😉 Any help would be greatly appreciated!

string mysql_error ([ resource $link_identifier ] ) 

But how do I use this? This just gives me the error, but I want the message to display with any error. Thanks

thanks for the info but I dont know how I could use this (it just gives me the error) — Hi from Deutschland

3 Answers 3

connect_error) < die("Connection failed: " . $conn->connect_error); > echo "Connected successfully"; ?> 

so I could replace code : echo «Please try later.» with code :

Remove the tags from your stuff. Also, I would remove the die() function. I also refined it again to wrap the success stuff in the else block.

Nice! This could lead me to this connection error solution: mysqli_real_connect(): The server requested authentication method unknown to the client

Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘user’@’localhost’ (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please

as per Wrikken’s recommendation below, check out a complete error handler for more complex, efficient and elegant solutions: http://www.php.net/manual/en/function.set-error-handler.php

Please, do not die. Echo an error message, but the use trigger_error(‘some internal error message’,E_USER_ERROR); , that way, the error shows up in your logs, as you are unlikely to be the one to catch it yourself on a busy site. Of course, this also assumes log_errors to be on, and display_errors to be off, which should be the default for any production environment.

$servername='localhost'; $username='root'; $password=''; $databasename='MyDb'; $connection = mysqli_connect($servername,$username,$password); if (!$connection) < die("Connection failed: " . $conn->connect_error); > /*mysqli_query($connection, "DROP DATABASE if exists MyDb;"); if(!mysqli_query($connection, "CREATE DATABASE MyDb;"))< echo "Error creating database: " . $connection->error; > mysqli_query($connection, "use MyDb;"); mysqli_query($connection, "DROP TABLE if exists employee;"); $table="CREATE TABLE employee ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP )"; $value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', 'johnsteve@yahoo.com')"; if(!mysqli_query($connection, $table))error;> if(!mysqli_query($connection, $value))error;>*/ 

Источник

Оцените статью