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

1

14

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?

Shope answered 29/12, 2011 at 17:47 Comment(7)
Uhm, do you want something different from "or die" or use OOP altogether? If the former, change title! if the latter, you can start from something as "low" as mysqli or go to a full ORM like Doctrine and Propel passing through PDOBedraggle
Look into using PDO. It is object-oriented, and can be configured to throw exceptions for error handling (actually it does by default)Trapeziform
I shed a tear every time I see the or die() method of "error handling", still so prevalent in online PHP tutorials.Trapeziform
@Alex - exceptions ( php.net/manual/en/language.exceptions.php )Kauri
@MarkBaker I knew what they are I was just suggesting that to the OP!Barny
by "a bunch of queries" you mean Transactions?Retha
@Alex, sorry, thought it was a question in response to Michael's commentKauri
A
19

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();
Aerodrome answered 29/12, 2011 at 17:50 Comment(4)
@Cyclone PDO is not inherently safer. If you are not using prepared statements you gain nothing by switching to PDO. It's not PDO === safe. It still depends on how you craft your queries.Retha
@Gordon, while you can hurt your app with either - I think you could make the point that there are more ways to hurt yourself, and it's easier to hurt yourself, by not using PDO.Aerodrome
not sure if I wouldnt want to say that. Not argueing about PDO being useful though if you need the db abstraction. Just saying that it still depends on the developer to create secure code.Retha
@Aaron, I recommend you start at the PHP PDO manual. You already know what a database is - so all you need now is use examples to start replacing your mysql calls. Make sure to read the user comments also!Aerodrome

© 2022 - 2024 — McMap. All rights reserved.