PHP Connect to MySQL
PHP 5 and above are recommended to connect to MySQL using the following methods:
- MySQLi extension ("i" stands for improved)
- PDO (PHP Data Objects)
In early versions of PHP, we used the MySQL extension. However, this extension was deprecated starting in 2012.
Should I use MySQLi or PDO?
If you need a short answer, it is "use whichever you are used to".
MySQLi and PDO each have their own advantages:
PDO works with 12 different databases, while MySQLi is only for the MySQL database.
Therefore, if your project needs to switch between multiple databases, it is recommended to use PDO, so you only need to modify the connection string and some query statements. With MySQLi, if you use a different database, you need to rewrite all the code, including queries.
Both are object-oriented, but MySQLi also provides a procedural API interface.
Both support prepared statements. Prepared statements can prevent SQL injection, which is very important for the security of web projects.
MySQLi and PDO Connect to MySQL Examples
In this chapter and the following chapters, we will use the following three ways to demonstrate PHP operating MySQL:
- MySQLi (Object-Oriented)
- MySQLi (Procedural)
- PDO
MySQLi Installation
Linux and Windows: When the php5 mysql package is installed, the MySQLi extension is automatically installed in most cases.
For detailed installation information, please see: http://php.net/manual/en/mysqli.installation.php
You can check whether the installation was successful via phpinfo():

PDO Installation
For detailed installation information, please see: http://php.net/manual/en/pdo.installation.php
You can check whether the installation was successful via phpinfo():

Connect to MySQL
Before we access the MySQL database, we need to connect to the database server first:
Example (MySQLi - Object-Oriented)
connect_error ) { die ( " Connection failed: " . $conn -> connect_error ) ; } echo " Connected successfully " ; ?>|
| Note that in the object-oriented example above, $connect_error was added in PHP 5.2.9 and 5.3.0. If you need to be compatible with earlier versions, please use the following code instead:
// 检测连接
if (mysqli_connect_error()) {
die("数据库连接失败: " . mysqli_connect_error());
} |
| --- | --- |
Example (MySQLi - Procedural)
Example (PDO)
getMessage ( ) ; } ?>![]() |
Note that in the PDO example above we have specified the database (myDB). PDO needs to set the database name during the connection process. If not specified, an exception will be thrown. |
|---|
Close the Connection
The connection is automatically closed after the script finishes executing. You can also use the following code to close the connection:
Example (MySQLi - Object-Oriented)
$conn->close();
Example (MySQLi - Procedural)
mysqli_close($conn);
Example (PDO)
$conn = null;