PHP Tutorial: Connecting to a database
PHP has three ways to connect to MySQL databases. These are called database APIs. There is a procedural version (mysqli_*) using simple functions. There are two object-oriented versions (MySQLi, PHP Data Objects (PDO)) which use classes. They are similar and return the same results.
The procedural version is often a better choice for beginners who may not know object-oriented programming yet. Many experienced PHP developers prefer the object-oriented versions. PDO is a popular choice for developers who need to work with other databases besides MySQL because the functions are not MySQL-specific.
By learning any one of these database APIs, it is easy to make the transition to another later. The concepts are the same and the function names are similar.
Procedural version using mysqli_*
There are five steps for database interaction in PHP.
- Create database connection
- Query database
- Work with returned results
- Free returned results
- Close database connection
Steps #1 and #5 should only happen once per PHP script. Steps #2–4 could happen once or many times in a single script.