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