Mysqli vs PDO - query/function execution

Asked

Viewed 367 times

1

Looking at questions here from the stack and the php.net website, I saw that query/function executions in Mysqli use if() to check whether it was executed or not, and the PDO uses try { ... } cacth() { ... }, example of connection to database according to PHP documentation

Mysqli:

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);
?>

PDO:

<?php
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

Why? Do you have any problem using inverted?

  • 1

    On mysqli you can choose to use exception or not natively. On PDO it is the normal mechanism. To throw a random exception (as in a DB error) I understand as a failure to understand the mechanism, in favor of programming "fashions" (such "good practices", which are only good for real in the academic world). Exception in PHP is usually something worthy of Rube Goldberg

  • For use with mysqli: https://secure.php.net/manual/en/mysqli-driver.report-mode.php in particular the flag MYSQLI_REPORT_STRICT that makes mysqli use exceptions

  • @Bacco can make a response by exemplifying how to treat possible errors (Exception)? With a list of errors and explaining what each one is

2 answers

5


Regardless of which option to take, how to enable configuration in My or If is important to know that when you invokes Try.. Catch means that PHP (in this case) goes into alert mode and prepares, if anything unexpected may occur, avoiding for example a pile burst. That is, it is not convenient to use this method for everything, an If will always be more performatic.

2

For PDO is easy and the documentation itself explains:

PDO::__Construct() throws a Pdoexception if the Attempt to connect to the requested database fails.

as the return of PDO, in case of error, is an exception, use try...catch is recommended.

Now, the documentation of mysqli_connect is vague as to the return. But, testing quickly if you know that the return is a Boolean and in negative case the error will be available in mysqli_connect_error. By the type of return a block is not necessary try..catch, although one can use:

<?php
$link = mysqli_connect('127.0.0.1', 'user', 'pass', 'db');

try {
    if (!$link) {
        throw new RuntimeException(mysqli_connect_error(), mysqli_connect_errno());
    }
} catch (RuntimeException $exception) {
    ...
}

UPDATE Or, as suggested by @Bacco, using mysqli_report and forcing exceptions to be thrown in case of errors:

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    $link = mysqli_connect('127.0.0.1', 'user', 'pass', 'db');
} catch (Exception $exception) {
    // caso haja um problema com a conexão, uma exceção será lançada
}    

As per the manual, mysqli_connect is a shortcut to mysqli::__construct, we can observe that the return should be an object representing the connection, but it is not for calls directly via mysqli_connect:

Returns an Object which represents the Connection to a Mysql Server.

In practical terms: use try..catch with the PDO, since without it an error cannot be contained and treated and use or if or try..catch for mysqli, as both can be used.

Sources:

  • Any advantage you use try catch in relation to mysqli if()?

  • @Guilhermecostamilam, depends on how your application is being made. With exceptions you leave the language taking care of it for you, with ifs, you will have to include it during your code, whether during connection with the bank or during a query, for example. Both will end up having the same result anyway.

  • 1

    @Bacco added an update dealing with mysqli_report. Thank you.

  • Beauty, but you don’t even have to leave the credits to me. I commented just not to leave the information incomplete.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.