PHP Tutorial: Connecting to a database

Yassine Himite
Geek Culture
Published in
7 min readJul 30, 2022

--

Photo by benofthenorth on Unsplash

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.

  1. Create database connection
  2. Query database
  3. Work with returned results
  4. Free returned results
  5. 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.

Set up access and credentials

--

--

Yassine Himite
Geek Culture

You don’t need to be a genius or a visionary, or even a college graduate for that matter, to be successful. You just need a framework and a dream.