So far, your PHP programs forget everything when the script ends. Sessions and files help a little, but a real site needs a proper place to keep data: users, posts, products, orders. That place is a database.
MySQL is one of the most popular databases in the world. It is free, fast and works very well with PHP. (MariaDB is a close relative with the same commands. Most of what you learn here works on both.)
A database is a set of tables
MySQL is a relational database. Data lives in tables, much like spreadsheets.
| id | name | |
|---|---|---|
| 1 | Ana | ana@example.com |
| 2 | Ben | ben@example.com |
| 3 | Cy | cy@example.com |
- The whole table is called
users. - Each horizontal line is a row (also called a record).
- Each vertical part is a column (also called a field):
id,name,email. - The
idcolumn is the primary key: a unique number for each row.
A database holds many tables (users, posts, orders), and tables can be related to each other, for example each post has a user_id that points to a row in users.
What is SQL?
SQL (Structured Query Language) is the language you use to talk to a database. Four commands do most of the work:
| Command | Does |
|---|---|
SELECT | Reads rows |
INSERT | Adds a row |
UPDATE | Changes rows |
DELETE | Removes rows |
SELECT name, email FROM users WHERE id = 2;
INSERT INTO users (name, email) VALUES ('Dev', 'dev@example.com');
UPDATE users SET name = 'Benjamin' WHERE id = 2;
DELETE FROM users WHERE id = 3;
This course teaches the small amount of SQL you need as you go. It is not a full SQL course.
How PHP and MySQL work together
- PHP connects to the MySQL server with a username and password.
- PHP sends an SQL command as text.
- MySQL runs it and sends back the result (rows, or a success message).
- PHP reads the result and builds the page.
The next lessons show each step with PDO, the PHP Data Objects extension.
Where is MySQL?
- Local development: XAMPP, Laragon, MAMP and AMPPS install MySQL (or MariaDB) for you, and include phpMyAdmin, a web page for browsing and editing your database.
- Web hosting: nearly every host offers MySQL, with a control panel to create databases and users.
- Docker: the official
mysqlandmariadbimages.
Other databases
PHP also works with PostgreSQL, SQLite, SQL Server and more. PDO gives you almost the same code for all of them. We use MySQL because it is the most common with PHP.
Why this matters in WordPress and Laravel
wp_posts, wp_users). Laravel’s database layer builds the same SQL for you. Understanding tables, rows and SQL makes both easier to understand.