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?
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.
die() function in PHP The die() function prints a message and exits the current script.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With