Rewrite Old MySQL-PHP Code with Deprecated MySQL_* Functions
As PHP continues to evolve, certain functions become obsolete and are replaced with more efficient and secure alternatives. One such change involves the deprecation of the mysql_* functions in favor of prepared statements and PDO (PHP Data Objects).
Connecting to the Database
When establishing a database connection, the following code can be updated:
// Old (mysql_connect) $conn = mysql_connect('127.0.0.1', 'root', 'pass'); // New (PDO) $db = new PDO('mysql:host=127.0.0.1;dbname=people;charset=UTF-8', 'root', 'pass');
Selecting the Database (MySQL Specific)
With the new PDO connection, selecting the database after establishing the connection is not necessary. The database name is specified in the connection string itself.
Database Class
Functions like __construct, __destruct, connect, selectDb are no longer needed with PDO. The connection string and PDO constructor handle most of the initialization and connection management.
Revised Code
The updated code below demonstrates the simplified approach for database connection and management using PDO:
// Updated Script class dbConn { protected $conn; public function __construct($connection_string) { try { $this->conn = new PDO($connection_string); } catch (PDOException $e) { die ("Error connecting to database: " . $e->getMessage()); } } public function __destruct() { if (!empty($this->conn)) $this->conn = null; } }
Conclusion
By utilizing PDO and ditching deprecated functions, developers can ensure their MySQL-PHP code is up-to-date, secure, and efficient. Remember that the specific implementation details may vary depending on the individual application.
The above is the detailed content of How Can I Modernize My Deprecated MySQL_* PHP Code Using PDO?. For more information, please follow other related articles on the PHP Chinese website!