MySQL Database

sa sahaya jerish Updated 20 Oct 2026
6 min read ·Lesson 144 of 155
In this post

Why Applications Need a Database In simple terms: Most web applications must remember things: user accounts, products, orders, blog posts, and comments. Storing them in files becomes unmanageable as s

Why Applications Need a Database

In simple terms: Most web applications must remember things: user accounts, products, orders, blog posts, and comments. Storing them in files becomes unmanageable as soon as data grows, many users write at the same time, or you need to search and combine information ("all orders from Chennai customers this month"). A database stores data in an organized way and answers such questions quickly and safely.

Technically: MySQL is an open-source relational database management system (RDBMS). It stores data in tables made of rows and columns, enforces rules (data types, unique values, relationships), and is queried with SQL (Structured Query Language). PHP communicates with MySQL through the MySQLi or PDO extensions. MariaDB, a community fork of MySQL, is largely compatible and works with the same PHP code.

Why MySQL With PHP?

ReasonExplanation
Widely availableIncluded in practically every hosting plan and cloud platform
ProvenPowers WordPress, Drupal, Magento, and countless custom applications
Free and open sourceMySQL Community Edition and MariaDB cost nothing
Excellent PHP supportTwo mature extensions: MySQLi and PDO
Scales wellFrom a small blog to large e-commerce systems

 


Relational Database Concepts

Database: gocourse_shop
│
├── Table: customers                    ├── Table: orders
│   ┌────┬───────┬──────────────────┐   │   ┌─────┬─────────────┬─────────┬────────┐
│   │ id │ name  │ email            │   │   │ id  │ customer_id │ status  │ total  │
│   ├────┼───────┼──────────────────┤   │   ├─────┼─────────────┼─────────┼────────┤
│   │ 1  │ Asha  │ asha@example.com │◄──┼───│ 501 │ 1           │ paid    │ 380.00 │
│   │ 2  │ Bala  │ bala@example.com │◄──┼───│ 502 │ 2           │ pending │ 1299.00│
│   └────┴───────┴──────────────────┘   │   └─────┴─────────────┴─────────┴────────┘

 

TermMeaningExample
DatabaseA container for related tablesgocourse_shop
TableA collection of records of one kindcustomers, orders
Row (record)One itemThe customer Asha
Column (field)One attribute with a data typeemail VARCHAR(255)
Primary keyA column that uniquely identifies each rowcustomers.id
Foreign keyA column referring to another table's primary keyorders.customer_id → customers.id
IndexA structure that speeds up searches on columnsAn index on customers.email
QueryAn SQL statement that reads or changes dataSELECT name FROM customers WHERE id = 1

 

Instead of repeating the customer's name and email in every order, each order stores only customer_id. This avoids duplicated data (a principle called normalization) and keeps information consistent: changing Asha's email updates it everywhere.

The Main SQL Statements

StatementPurposeLesson
CREATE DATABASE / CREATE TABLEDefine structureMySQL Create DB, MySQL Create Table
INSERTAdd rowsMySQL Insert Data
SELECTRead rowsMySQL Select Data, MySQL Where, MySQL Order By, MySQL Limit Data
UPDATEChange rowsMySQL Update Data
DELETERemove rowsMySQL Delete Data
JOINCombine rows from several tablesMySQL Joins with PHP

 


MySQLi vs PDO

PHP offers two extensions for MySQL:

FeatureMySQLiPDO
Databases supportedMySQL / MariaDB onlyMySQL, PostgreSQL, SQLite, SQL Server, Oracle, and more
API styleObject-oriented and proceduralObject-oriented
Prepared statementsYes (? placeholders)Yes (? and named :placeholders)
MySQL-specific featuresFull access (multi-queries, async queries)Most common features
Used byMany legacy projects, WordPressLaravel, Symfony/Doctrine, most modern code

 

Both are secure when used with prepared statements. This section first teaches MySQLi (lessons 193–207), then PDO (lessons 208–213). For new projects, PDO is usually the preferred choice because the same API works with other databases.

Note: The old mysql_* functions (mysql_connect(), mysql_query()) were removed in PHP 7.0. Tutorials using them are outdated and insecure.


Setting Up MySQL for Development

Option 1: An All-in-One Package

Packages such as XAMPP, Laragon, or MAMP install Apache, PHP, and MySQL/MariaDB together, with phpMyAdmin for managing databases in the browser.

Option 2: Docker

docker run --name gocourse-mysql \
  -e MYSQL_ROOT_PASSWORD=change-this-root-password \
  -e MYSQL_DATABASE=gocourse_shop \
  -e MYSQL_USER=gocourse_app \
  -e MYSQL_PASSWORD=change-this-app-password \
  -p 3306:3306 \
  -d mysql:8.4

 

This starts a MySQL 8.4 server (a long-term-support release), creates the gocourse_shop database, and creates an application user with access to it.

Option 3: Native Installation

On Ubuntu: sudo apt install mysql-server (or mariadb-server), then secure the installation with sudo mysql_secure_installation.

Checking the PHP Extensions

<?php
var_dump(extension_loaded('mysqli'));
var_dump(extension_loaded('pdo_mysql'));

 

Output (when both are installed)

bool(true)
bool(true)

 

If an extension is missing, install it (for example, sudo apt install php8.4-mysql on Ubuntu, which provides both) and restart PHP-FPM or the web server.


A Dedicated Database User

Applications should never connect as root. Create a user that has only the permissions the application needs:

CREATE USER 'gocourse_app'@'localhost' IDENTIFIED BY 'a-long-random-password';

GRANT SELECT, INSERT, UPDATE, DELETE ON gocourse_shop.* TO 'gocourse_app'@'localhost';

 

Why Least Privilege Matters

If an attacker ever finds a way to run SQL through your application, a restricted user cannot drop tables, read other databases, or create new users. Schema changes (creating and altering tables) are performed by a separate account during deployment, not by the running application.


The Example Database for This Section

The following lessons build and use a small shop database:

TablePurposeKey Columns
customersRegistered customersid, name, email (unique), city
productsProduct catalogid, sku (unique), name, price, stock
ordersOrders placed by customersid, customer_id → customers, status, total
order_itemsProducts in each orderorder_id → orders, product_id → products, quantity, unit_price

 

Creating these tables is shown step by step in MySQL Create DB and MySQL Create Table.


How PHP Talks to MySQL

Browser ──HTTP──► PHP script ──SQL over a connection──► MySQL server
                      ▲                                      │
                      └──────────── result rows ◄────────────┘

 

  1. PHP opens a connection to the MySQL server using a host, port, username, password, and database name.
  2. It sends SQL statements — always with prepared statements when user input is involved.
  3. MySQL returns results: rows for SELECT, affected-row counts for INSERT/UPDATE/DELETE.
  4. PHP turns the rows into arrays or objects and generates the response.

Common Mistakes

Using the Removed mysql_* Functions

Effect: Fatal "Call to undefined function" errors in PHP 7+.

Fix: Use MySQLi or PDO.

Connecting as root

Effect: A single vulnerability can compromise the entire database server.

Fix: Create a dedicated user with minimal privileges.

Building SQL From User Input by Concatenation

Effect: SQL injection (see SQL Injection Prevention).

Fix: Always use prepared statements.

Storing Everything in One Big Table

Effect: Duplicated, inconsistent data.

Fix: Design related tables connected by keys.


Best Practices

  • Use MySQL 8.x or a current MariaDB release, with the utf8mb4 character set.
  • Choose PDO for new projects; understand MySQLi for existing code.
  • Give the application its own database user with least privilege.
  • Use prepared statements for every query that includes external values.
  • Keep database credentials in environment variables, never in code.

Official reference: https\://www.php.net/manual/en/book.mysqli.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery
Ask about this post
AI Ask about this post

Ask questions about MySQL Database and get answers drawn from it.

Signed-in readers only.