PHP MySQL Database

PHP Tutorial

🗄️ PHP MySQL Database

Using PHP with MySQL allows you to store, retrieve, update, and delete data from a database—this is the backbone of dynamic websites and web applications.

We’ll cover everything step by step, from connection to queries, with examples + interview questions.


1️⃣ What is PHP MySQL?

  • PHP → server-side scripting language

  • MySQL → relational database

  • PHP + MySQL = dynamic, data-driven websites

📌 Examples: Login system, registration, e-commerce, admin panels


2️⃣ Ways to Connect PHP with MySQL

PHP provides two main APIs:

Method Description Usage
MySQLi Improved MySQL Most common
PDO PHP Data Objects More secure & flexible

👉 We’ll focus mainly on MySQLi (interview + practical friendly)


3️⃣ Create MySQL Database

CREATE DATABASE testdb;

4️⃣ Create Table

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);

5️⃣ PHP MySQL Connection (MySQLi) ⭐

Connection Code


 

📌 Always check connection errors


6️⃣ Insert Data into MySQL ⭐


 


7️⃣ Fetch Data from Database ⭐

Fetch Multiple Records


 


8️⃣ Update Data ⭐


 


9️⃣ Delete Data ⭐



 

⚠️ Always use WHERE to avoid deleting all rows.


🔟 Prepared Statements (Security – Very Important) ⭐⭐

Protects against SQL Injection.


 

✔ Mandatory for interviews & real projects


1️⃣1️⃣ Close Database Connection



 

✔ Frees server resources


1️⃣2️⃣ MySQLi vs PDO ⭐ (Interview Favorite)

Feature MySQLi PDO
Database support MySQL only Multiple DBs
Prepared statements ✔ Yes ✔ Yes
OOP support
Interview usage ✔ Very common ✔ Advanced

1️⃣3️⃣ Common Mistakes ❌

❌ Not checking DB connection
❌ Using plain queries (SQL injection risk)
❌ Forgetting WHERE in UPDATE/DELETE
❌ Not closing connection
❌ Hardcoding credentials in public files


📌 Interview Questions & MCQs (Very Important)

Q1. Which function connects PHP to MySQL?

A) mysql_connect()
B) mysqli_connect()
C) connect_mysql()
D) db_connect()

Answer: B


Q2. Which method is more secure?

A) Normal queries
B) Prepared statements

Answer: B


Q3. Which function fetches associative array?

A) mysqli_fetch()
B) mysqli_fetch_assoc()
C) mysqli_fetch_row()
D) mysqli_result()

Answer: B


Q4. What does PDO stand for?

A) PHP Data Object
B) PHP Database Option
C) Program Data Object
D) Private Data Object

Answer: A


Q5. Which SQL command retrieves data?

A) INSERT
B) UPDATE
C) SELECT
D) DELETE

Answer: C


🔥 Real-Life Use Cases

✔ Login & registration system
✔ CRUD applications
✔ Admin dashboards
✔ E-commerce websites
✔ CMS systems


✅ Summary

  • PHP + MySQL = dynamic websites

  • Use MySQLi or PDO

  • Always use prepared statements

  • Perform CRUD operations

  • Close DB connection

  • Core topic for PHP interviews & projects

You may also like...