Should I use "or die"?

6

I saw this question Display mysqli error using die and I was wondering should I use always the or die or is it just for those who are starting to see that it gave problem?

$sql = $mysqli->query( "SELECT * FROM tabela" ) or die ( mysqli_error( ) );
    
asked by anonymous 21.07.2016 / 10:30

3 answers

6

I think it's a bad practice inherited from basic language lessons.

The first PHP tutorials with MySQL, including the official manual, show examples of connecting to MySQL like the one you posted in the question:

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

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

Normally, die or exit is used to debug, creating breakpoints because these commands stop execution at the moment it is invoked.

    
21.07.2016 / 16:51
3

I believe everything will depend on the context you are working on. The bad side of using die is that your execution will end there anyway. Independent of error.
Using other methods like try/catch you will have the opportunity to work with Exception to customize and minimize failing.

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 the two 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 have helped.
Font

    
21.07.2016 / 16:31
-1

If you believe that your application will not work without something you should throw an exception, but die works as well.

When you throw an exception you can give more information about the error and handle 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 becomes more and more complicated to find out where you gave error so the exceptions in theory are there to help you.

    
21.07.2016 / 15:33