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

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

Susan Sarandon
Release: 2024-10-26 09:43:30
Original
941 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template