"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Modernize Your MySQL-PHP Code: Replacing Deprecated `mysql_*` Functions with Prepared Statements and PDO?

How to Modernize Your MySQL-PHP Code: Replacing Deprecated `mysql_*` Functions with Prepared Statements and PDO?

Published on 2024-11-03
Browse:798

How to Modernize Your MySQL-PHP Code: Replacing Deprecated `mysql_*` Functions with Prepared Statements and PDO?

Rewriting Old MySQL-PHP Code with Deprecated mysql_* Functions

As PHP evolves, certain functions become deprecated, including the mysql_* commands. To enhance security and stability, these commands should be replaced with prepared statements and PDO.

Key Replacements:

  • Replace mysql_connect with PDO::__construct().
  • Replace mysql_select_db with setting the database name in the PDO connection string, e.g., mysql:host=127.0.0.1;dbname=people.

Code Sample:

 // Old deprecated code
$db = new dbConn('127.0.0.1', 'root', 'pass', 'people', 'animals');

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

Additional Considerations:

  • Constructor and Destructor: The __construct() and __destruct() functions are not necessary with PDO, as it handles connection and closing internally.
  • Database Selection: Database selection is now embedded in the PDO connection string. Use the dbname parameter in the connection string to specify the desired database.

Example Class:

The following example class demonstrates how to rewrite the selectDb method using PDO:

class DB
{
    private $pdo;

    public function __construct($host, $db, $user, $pass)
    {
        // Establish PDO connection
        $this->pdo = new PDO("mysql:host=$host;dbname=$db;charset=UTF-8", $user, $pass);
    }

    public function selectDatabase($dbName)
    {
        // No longer required with PDO
    }
}

Conclusion:

By replacing deprecated mysql_* functions with prepared statements and PDO, developers can enhance the security and stability of their code while simplifying database interactions.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3