May 11, 2021 PHP
2. Should I use MySQLi or PDO?
3. MySQLi and PDO connect MySQL instances
7. Instances (MySQLi - Object Oriented)
8. Instances (MySQLi - Process Oriented)
11.. Instances (MySQLi - Object Oriented)
PhP 5 and above recommend connecting MySQL in the following ways:
We used the MySQL extension in the PHP early-morning version. However, the extension has not been recommended since 2012.
If you need a short answer, "You're used to which one."
MySQLi and PDO have their own advantages:
PDO is applied in 12 different databases, and MySQLi is only for MySQL databases.
Therefore, if your project needs to switch between multiple databases, PDO is recommended so that you only need to modify the connection string and some query statements. With MySQLi, if different databases, you need to re-all the code, including queries.
Both are object-oriented, but MySQLi also provides an API interface.
Both support preprocessed statements. Preprocessed statements prevent SQL injection and are important for the security of web projects.
In this and subsequent chapters, we'll demonstrate PHP operation MySQL in three ways:
Linux and Windows: MySQLi extensions are automatically installed when the php5 mysql package is installed.
For installation details, see: http://php.net/manual/en/mysqli.installation.php
For installation details, see: http://php.net/manual/en/pdo.installation.php
Before we can access the MySQL database, we need to connect to the database server:
Note that in the object-oriented $connect above, the error was added in PHP 5.2.9 and 5.3.0. I
f you need to be compatible with earlier versions, replace it with the following code:
Detect the connection if (mysqli_connect_error()) { die("Database connection failed: " . m ysqli_connect_error()); } |
Note that we have specified a database (myDB) in the PDO instance above. T he PDO needs to set the database name during the connection process. If not specified, an exception is thrown. |
The connection closes automatically after the script is executed. You can also use the following code to close the connection: