A Comprehensive Beginner’s Guide to MySQL Databases Using PHP
Step 1: Introduction to Databases
A database is a structured collection of information. In web development, MySQL is one of the most widely used relational database management systems (RDBMS). Key concepts:
-
Database → a container for data. Example:
company_db -
Table → stores specific types of data. Example:
employees -
Row (Record) → a single entry in a table
-
Column (Field) → attributes of the record. Example:
name,email,salary
In relational databases, data is organized systematically and can be queried efficiently.
Step 2: Install MySQL and PHP
Before we begin coding:
-
Install XAMPP, WAMP, or MAMP (includes Apache + PHP + MySQL).
-
Start Apache and MySQL from your control panel.
-
Open phpMyAdmin to manage databases graphically, or use the terminal.
Step 3: Establish a PHP-MySQL Connection
Create a file named db_connect.php:
Explanation:
-
mysqli→ PHP extension for MySQL -
connect_error→ checks if the connection fails -
CREATE DATABASE IF NOT EXISTS→ ensures idempotency
Step 4: Create a Table
Now, create a table to store employees:
Explanation:
-
INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY→ unique identifier for each employee -
VARCHAR(50)→ text fields with max 50 characters -
DECIMAL(10,2)→ numerical field for salaries with 2 decimal places -
NOT NULL→ ensures that field must have a value
Step 5: Insert Records
Add some employees:
Explanation:
-
Each row represents a single employee record
-
Use commas to insert multiple records at once
Step 6: Read Records
Retrieve all employees:
Explanation:
-
$result->num_rows→ number of rows returned -
$row = $result->fetch_assoc()→ fetch a single record as an associative array
Step 7: Update Records
Modify an employee’s salary:
Explanation:
-
UPDATE table SET column=value WHERE condition→ modifies existing data -
Always include
WHEREto prevent updating all rows unintentionally
Step 8: Delete Records
Remove an employee:
Explanation:
-
DELETE FROM table WHERE condition→ removes specific records -
Always double-check your condition to avoid accidental data loss
Step 9: Close Connection
After all operations:
Explanation:
-
Properly closing the connection ensures resources are freed
-
Essential for maintaining server performance
Step 10: Summary
In this tutorial, we learned:
-
How to connect PHP to MySQL
-
How to create a database and table
-
How to insert, read, update, and delete records
-
Why structured queries are important in relational databases
This forms the foundation for building dynamic web applications with a database backend