Home > Article > Backend Development > Here are a few title options, crafted to be question-based and reflect the article\'s content: Option 1 (Direct & Concise): * How to Rewrite Deprecated MySQL-PHP Code with PDO? Option 2 (Benef
Rewriting Deprecated MySQL-PHP Code with PDO
The deprecation of mysql_* functions in PHP demands a transition to a more secure and robust alternative. Here's a guide to successfully rewrite old code using PDO.
Replacing the Connection and Database Selection
In the old code:
<code class="php">$db = new dbConn('127.0.0.1', 'root', 'pass', 'people', 'animals'); $db->connect(); $db->selectDb($database);</code>
In PDO:
<code class="php">$db = new PDO('mysql:host=127.0.0.1;dbname=people;charset=UTF-8', 'root', 'pass');</code>
The PDO constructor handles both connection and database selection. The connection string specifies the host, database, and charset.
Removing Unnecessary Functions
Functions like __construct, __destruct, connect, and selectDb are no longer needed in PDO. PDO provides these features automatically.
Maintaining Database Class
If you prefer to have a database class, you can extend PDO:
<code class="php">class DB extends PDO { ... Your custom code }</code>
This allows you to add functionality specific to your application while leveraging the benefits of PDO.
Conclusion
By following these guidelines, you can effectively rewrite old MySQL-PHP code using PDO. The transition not only enhances security but also simplifies your code and improves performance.
The above is the detailed content of Here are a few title options, crafted to be question-based and reflect the article\'s content: Option 1 (Direct & Concise): * How to Rewrite Deprecated MySQL-PHP Code with PDO? Option 2 (Benef. For more information, please follow other related articles on the PHP Chinese website!