Home  >  Article  >  Backend Development  >  How can I rewrite legacy PHP code using deprecated `mysql_*` functions?

How can I rewrite legacy PHP code using deprecated `mysql_*` functions?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 09:43:30809browse

How can I rewrite legacy PHP code using deprecated `mysql_*` functions?

Rewriting Legacy PHP Code with Deprecated mysql_* Functions

As you've discovered, mysql_* functions in PHP have been deprecated due to security and stability concerns. To effectively rewrite your code, consider the following guidelines:

1. Switch to PDO or Prepared Statements:

Replace mysql_* functions with PDO or prepared statements to improve security and avoid SQL injection vulnerabilities.

2. Reconfigure Database Connection:

The database connection should be established using a connection string instead of individual parameters. For example:

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

3. Remove Unnecessary Constructor and Destructor:

Functions like __construct and __destruct are no longer necessary with PDO. PDO handles database connection and cleanup internally.

4. Simplified Database Selection:

To select a database with PDO, use the exec method:

<code class="php">$db->exec("USE " . $database);</code>

5. Consider Database Class Extension:

If desired, you can extend from PDO to create your own database class with custom functionality.

Example Rewrite:

Your original script can be rewritten as follows using PDO:

<code class="php">class dbConn extends PDO
{
    public function connect()
    {
        try {
            parent::__construct('mysql:host=127.0.0.1;dbname=people;charset=UTF-8', 'root', 'pass');
        } catch (PDOException $e) {
            die('Database connection failed: ' . $e->getMessage());
        }
    }

    public function selectDb($database)
    {
        $this->exec("USE " . $database);
        $this->query("SET NAMES 'utf8'");
    }
}</code>

Remember, switching to PDO or prepared statements not only enhances security but also simplifies code maintenance and improves performance.

The above is the detailed content of How can I rewrite legacy PHP code using deprecated `mysql_*` functions?. 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