How PHP Connects to MySQL
Posted: Sat Apr 25, 2026 6:42 pm
How PHP Connects to MySQL Securely (Step-by-Step)
Many dynamic websites use a database to store information such as users, posts, comments, products, settings or logs.
PHP can connect to MySQL or MariaDB and work with this data. In this guide we use PDO, because it supports prepared statements and is a good modern choice for secure PHP database access.
1. What You Need
On Debian or Ubuntu:
Restart Apache:
If you use PHP-FPM:
3. Create a Database and Limited User
Log in to MySQL or MariaDB:
Create the database:
Create a database user:
Give only the permissions needed for a normal application:
…login to view the rest of this post
Many dynamic websites use a database to store information such as users, posts, comments, products, settings or logs.
PHP can connect to MySQL or MariaDB and work with this data. In this guide we use PDO, because it supports prepared statements and is a good modern choice for secure PHP database access.
1. What You Need
- A web server such as Apache or Nginx
- PHP installed
- MySQL or MariaDB installed
- The PHP MySQL module
- A database name
- A database user with limited permissions
On Debian or Ubuntu:
Code: Select all
sudo apt update
sudo apt install php-mysql
Code: Select all
sudo systemctl restart apache2
Code: Select all
sudo systemctl restart php8.4-fpm
Log in to MySQL or MariaDB:
Code: Select all
sudo mysql
Code: Select all
CREATE DATABASE testdb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Code: Select all
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'CHANGE_THIS_TO_A_LONG_RANDOM_PASSWORD';
Code: Sele