Should I use the «or die»?

Asked

Viewed 3,191 times

6

I saw this question Display mysqli error using die and I got to thinking I should always wear the or die or is it just for those who are just beginning to see that it gave problem?

$sql = $mysqli->query( "SELECT * FROM tabela" ) or die ( mysqli_error( ) );
  • 2

    I practically answered here a few hours ago: http://answall.com/a/141797/70 (but as you mentioned, I complemented and highlighted the relevant part)

  • 4

    Some say that every PHP script should start with die() :D

3 answers

6


I believe it is a bad practice inherited from basic language lessons.

The first tutorials of PHP with Mysql, including the official manual, show examples of connection with Mysql as the one posted in the question:

$sql = $mysqli->query( "SELECT * FROM tabela" ) or die ( mysqli_error( ) );

In order to simplify teaching for beginners, this is taught in this way. However, it is considered bad practice to apply this in the "real world".

It is usually used die or exit to debug, creating breakpoints as these commands interrupt execution at the time it is invoked.

4

I believe that everything will depend on the context that you are working.
The side 'bad' to use the die is that your execution will end up right there. Regardless of the error.
Using other methods such as try/catch you will have the opportunity to work with Exception to customize and minimize failure.

try {
    $sql = $mysqli->query( "SELECT * FROM tabela" );
} catch (Exception $e) {
    //$e->getMessage();
    //Aqui você pode redirecionar pra outra página, exibir uma mensagem personalizada ou qualquer coisa melhor do que parar sua aplicação.
}

You can still use both together in specific cases:

try {
    $sql = $mysqli->query( "SELECT * FROM tabela" );
} catch (Exception $e) {
    try {
       //faça algo como segunda opção
    } catch (Exception $i) {
       die ('Falha: ' . $i->getMessage());
    }
}

I think everything will depend on the context and how much you want to keep your user in your application.

I hope I’ve helped.
Source

  • I do not understand why they gave -1 to this answer.

  • 4

    The important thing is that she helped you Jorge. If somehow I could help you I was already satisfied. Regardless of the vote.

-1

If you believe that your application will not work without something you should play an exception, but the die works also.

When you play an exception you can give more information about the error and treat it more appropriately, in a large application it is important to have a trace to help you maintain the code. In the case when you have many classes interacting with each other it gets more and more complicated you discover where you went wrong then the exceptions in theory are there to help you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.