Databases are essential for dynamic web applications. MySQL is one of the most popular relational database management systems (RDBMS) used with PHP. In this lesson, you will learn how to set up a MySQL database and connect it to PHP using PDO and MySQLi.
13.1 Setting Up a Database
What is MySQL?
- MySQL: An open-source relational database system for managing data.
- Uses:
- Storing user data.
- Managing inventory.
- Handling financial transactions.
Steps to Set Up a MySQL Database
Step 1: Install MySQL
- MySQL is often bundled with tools like XAMPP, WAMP, or MAMP.
- If not installed, download and install MySQL from the MySQL website.
Step 2: Access the MySQL Interface
- Using phpMyAdmin:
- Open
http://localhost/phpmyadmin
. - Login with:
- Username:
root
- Password: Leave blank (default for XAMPP/WAMP).
- Username:
- Open
- Using MySQL Command-Line Interface (CLI):
Step 3: Create a Database
- Using phpMyAdmin:
- Go to the
Databases
tab. - Enter a name for the database (e.g.,
test_db
). - Click
Create
.
- Go to the
- Using MySQL CLI:
- Verify Database:
Step 4: Create a Table
- Using phpMyAdmin:
- Select your database.
- Go to the
SQL
tab and run the following query:
- Using MySQL CLI:
Insert Sample Data
- SQL Query:
13.2 Connecting PHP with MySQL
Methods of Database Connection
- MySQLi:
- Procedural and object-oriented interface.
- Supports MySQL only.
- PDO (PHP Data Objects):
- Object-oriented interface.
- Supports multiple databases (MySQL, PostgreSQL, SQLite, etc.).
Connecting Using MySQLi
Procedural MySQLi
Object-Oriented MySQLi
Connecting Using PDO
Basic Connection
Querying the Database
Using MySQLi
Procedural:
Object-Oriented:
Using PDO
Error Handling in Connections
MySQLi Procedural
PDO with Exception
Practical Example: User Management
Insert Data
Using PDO
Delete Data
Activities and Exercises
- Database Setup:
- Create a database
library
with a tablebooks
(columns:id
,title
,author
,published_year
).
- Create a database
- Basic Connection:
- Write a script to connect to the
library
database using both MySQLi and PDO.
- Write a script to connect to the
- CRUD Operations:
- Implement Create, Read, Update, and Delete operations for the
books
table using PDO.
- Implement Create, Read, Update, and Delete operations for the
Assignment
- Create a
tasks
table with the following structure:id
(INT, Auto Increment, Primary Key)task_name
(VARCHAR, 100)status
(ENUM:pending
,completed
)
- Implement the following using PHP and MySQL:
- Insert a new task into the
tasks
table. - Display all tasks in a table format.
- Update the status of a task.
- Delete a task.
- Insert a new task into the
Summary
In this lesson, you learned:
- How to set up a MySQL database and create tables.
- How to connect PHP with MySQL using MySQLi and PDO.
- How to perform basic CRUD operations.
These skills form the foundation for creating dynamic web applications. Let me know if you’d like more examples or exercises!
Leave a Reply