質問

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?

役に立ちましたか?

解決

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();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top