The best PHP MySQL connection Tutorial In 2024, In this tutorial you can learn I use the MySQLi, or PDO?,MySQLi and PDO connection MySQL instance,MySQLi installation,PDO installation,MySQL connection,Examples (MySQLi - Object Oriented),Examples (MySQLi - process-oriented),Examples of (PDO),Close connection,Examples (MySQLi - Object Oriented),Examples (MySQLi - process-oriented),Examples of (PDO),
PHP 5 or higher and recommends the following ways to connect MySQL:
In early versions of PHP, we use MySQL extension. However, the expansion in 2012 is not recommended.
If you need a short answer, that is, "what you used to use which."
MySQLi and PDO have their own advantages:
PDO applications in 12 different databases, MySQLi only for the MySQL database.
So, if you need to switch the project in a variety of databases, it is recommended to use PDO, so you only need to modify the connection string and departments can query. Use MySQLi, if a different database, you need to re-write all the code, including queries.
Both are object-oriented, but also provides a MySQLi API interface.
Both support prepared statements. Prepared statements to prevent SQL injection, for the security of web projects is very important.
In this chapter and the next chapter, we will use the following three ways to demonstrate PHP operate MySQL:
Linux and Windows: When MySQLi extension php5 mysql package is installed in most cases is installed automatically.
Installation For more information, please see: http://php.net/manual/en/mysqli.installation.php
Through phpinfo () to see if the installation was successful:
For installation details, please see: http://php.net/manual/en/pdo.installation.php
Through phpinfo () to see if the installation was successful:
Before we visit the MySQL database, we need to connect to the database server:
Note that in the above example object-oriented $ connect_error in PHP 5.2.9 and 5.3.0 are added. If you need compatibility with earlier versions, please use the following code to replace: // Test connection if (mysqli_connect_error ()) { die ( "Database connection failed:". mysqli_connect_error ()); } |
Note that in the above example we have specified the PDO database (myDB). PDO during the connection you need to set the database name. If not specified, an exception is thrown. |
Connection will automatically close after the script execution. You can also use the following code to close the connection: