Home  >  Article  >  Backend Development  >  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?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 18:25:03616browse

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:

<code class="php"> // 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');</code>

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:

<code class="php">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
    }
}</code>

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.

The above is the detailed content of How to Modernize Your MySQL-PHP Code: Replacing Deprecated `mysql_*` Functions with Prepared Statements and PDO?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn