How PHP Connects to MySQL

Discussion forum for web development. Covers frontend and backend technologies including HTML, CSS, JavaScript, PHP and modern frameworks. Topics include websites, web applications, APIs, UI/UX, performance, debugging and server-side development. Suitable for beginners and experienced developers.
Post Reply
MegaTux
Posts: 62
Joined: Thu Apr 16, 2026 6:21 am

How PHP Connects to MySQL

Post by MegaTux »

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
  • 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
2. Install PHP MySQL Support

On Debian or Ubuntu:

Code: Select all

sudo apt update
sudo apt install php-mysql
Restart Apache:

Code: Select all

sudo systemctl restart apache2
If you use PHP-FPM:

Code: Select all

sudo systemctl restart php8.4-fpm
3. Create a Database and Limited User

Log in to MySQL or MariaDB:

Code: Select all

sudo mysql
Create the database:

Code: Select all

CREATE DATABASE testdb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Create a database user:

Code: Select all

CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'CHANGE_THIS_TO_A_LONG_RANDOM_PASSWORD';
Give only the permissions needed for a normal application:

Code: Sele

login to view the rest of this post
Post Reply