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?

Aaron
  • 1,956
  • 5
  • 34
  • 56

1 Answers1

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();
Xeoncross
  • 55,620
  • 80
  • 262
  • 364
  • 2
    @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. – Gordon Dec 29 '11 at 17:54
  • @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. – Xeoncross Dec 29 '11 at 17:56
  • 1
    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. – Gordon Dec 29 '11 at 18:02
  • 3
    @Aaron, I recommend you start at the [PHP PDO manual](http://us2.php.net/pdo). 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!* – Xeoncross Dec 29 '11 at 18:50