php - Best practices for updating from mysql to PDO

581

I'm updating a code base from mysql to pdo and this is the first time I've done a project like this so I've been doing research on best practices and would like some input. Here is the old code:

$link = @mysql_connect('localhost', "xxx", "xxx")

 or die('Could not connect: ' . mysql_error());

mysql_select_db("xxx") or die('Could not select database');

In my code I'm putting all the login credentials into a separate file and using the ip address, username and password to connect as opposed to localhost.

try {
    $pdo = new PDO($dsn, $user, $password);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
    log_error("Failed to run query", $e->getMessage(), $e->getCode(), array('exception' => $e));
    die('Could not connect!');

Two questions, is this a good alternative to using the die method deal with errors and log to the client and also is this the correct way to connect? Is there an advantage to connecting using localhost vs the server IP address? Thanks for the help!

486

Answer

Solution:

Is this a good alternative to using the die method?

What you're doing is reasonable as part of a migration - it should behave the same way it did before. You might consider, however, not catching thatPDOException and allowing it to be thrown all the way up to your global error handler. That's nicer because it's less code, and you're not catching an exception just todie. But before making that change, you should have an idea of the way it will behave in your production systems (will you see the error in your logs)?

Is this the correct way to connect?

Yes, it seems like you're usingPDO correctly.

Is there an advantage to connecting using localhost vs the server IP address?

You mean in production? Best practice would be to run your database on a separate server - in which caselocalhost would obviously not work. If the load is light and you are running the database and PHP server on the same box for now, then it shouldn't matter either way.

621

Answer

Solution:

Good questions, and I already have all the answers for you (and even answers to questions you didn't ask yet), just follow my article, How to connect to MySQL using PDO.

To answer your questions more directly:

is this a good alternative to using the die method deal with errors

By all means - no.
To be honest, your current approach is not much better than the old one. The code here is inflexible, you have to edit it manually to change the behavior. It would be much better if your code would only throw an error, whereas its processing would be defined elsewhere and easily configurable.

Let alone thedie() is still there. Trust me, a site that tells you 'Could not connect!' on a white screen looks awfully unprofessional. You should never ever use die like that.

@mkasberg is right, generally, you don't catch an Exception but let it bubble up to where it will be appropriate to handle it. However, PDO connection is a special case as the stack trace in case of error would contain the db credentials which you likely don't want to show to anyone. To prevent this, I propose to throw a brand new exception that would contain the same error information but no stack trace.

is this the correct way to connect?

Apart from what was said above, without seeing the DSN we cannot tell for sure.

Is there an advantage to connecting using localhost vs the server IP address?

Generally, a hostname is preferred, like with any other service. the IP address could change but thanks to DNS system the domain name would always point at the correct address. However, localhost is a special case, and judging by many questions here on Stack Overflow I would rather recommend to use the IP address, as it could save you a headache or two, like a too big timeout when DNS is misconfigured.

People are also looking for solutions to the problem: php - Laravel 5.8 conditionally inserting sql snippet

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.