How to successfully rewrite old mysql-php code with deprecated mysql_* functions?

Actually, a simple, sweet and short: Yes, not necessary any longer.

Let's review the code not that we have lost something:

  • __construct - The constructor merely contained all the configuration. PDO has a much easier concept here, a connection string containing the most information:

     mysql:host=127.0.0.1;dbname=people;charset=UTF-8
    

    Also PDO provides the constructor for use ready-made, so double not necessary.

  • connect - The connection function is not necessary any longer as well. This is done by instantiating PDO already. You can look for exceptions, the PHP manual has an example on it's constructor page.

  • selectDb - This complicated function is not needed any longer as well. Wow, the third function we can just drop because of the PDO connection string. Much power with so less characters. Cheers!

  • __destruct - The destructor. Let's be fair: MySQL did not need this as well. However with PDO we get it for free - without writing a single line of code.

Looks good! You managed to migrate from that obscure database class to PDO by removing outdated code! Congratulations:

$db = new PDO('mysql:host=127.0.0.1;dbname=people;charset=UTF-8', 'root', 'pass');

If you now think, what about if I want to have database class on my own? Well you can do that, because you can extend from PDO (yes that works!):

class DB extends PDO
{
   ... my super-new-shiny-code
}

Why you might want to do that? No idea, but maybe it's more fluent for your code. If you're looking for a better code-example, I have one at PHP/MySQL Table with Hyperlinks.


I think the easiest way to switch the database inside your application will be:

$pdo_instance->query("USE people");

and

$pdo_instance->query("USE animals");

or the maybe better (and cleaner) way might be

$db_people = new PDO('mysql:host=127.0.0.1;dbname=people;charset=UTF-8', 'root', 'pass');

and

$db_animals = new PDO('mysql:host=127.0.0.1;dbname=animals;charset=UTF-8', 'root', 'pass');

If you mark a database in your class active, you can access the data with $db_people->query() or $db_animals->query().