Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Modern version of "or die();" for error handling

Tags:

oop

php

mysql

die

When I first started learning PHP, I would write query statements similar to the one here:

mysql_query("SELECT * FROM `table`") or die(mysql_error());

What is the best, present-day way, to achieve the same effect as the above?

To my understanding, in today's world with classes, functions, and general OOP, running a bunch of queries in this manner is very inefficient. What should we be doing differently?

like image 200
Aaron Avatar asked Dec 29 '11 17:12

Aaron


People also ask

Which function is used for PHP error handling?

In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function.

What is the use of die in PHP?

die() function in PHP The die() function prints a message and exits the current script.

What is the purpose of error Handling in PHP explain with suitable example?

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences. Its very simple in PHP to handle an errors.

What is Exception Handling in PHP explain?

Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception. This is what normally happens when an exception is triggered: The current code state is saved.


1 Answers

You should be using PDO which will throw exceptions which can be caught - or if not caught they will kill the script the same as die().

$db = new \PDO(
    'mysql:dbname=database;host=localhost',
    'root',
    '',
    array(
        \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
        \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
        \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION
    )
);

$db->query('SELECT INVALID FOO'); // Exception!!!

this_never_gets_run();
like image 139
Xeoncross Avatar answered Sep 24 '22 03:09

Xeoncross