Mastering PHP: From Basics to Building Dynamic Web Applications

0 0 0 0 0

Chapter 7: PHP with MySQL (Database Integration)

🔹 1. Introduction

One of PHP’s strongest features is its seamless integration with MySQL, a powerful relational database management system. Together, PHP and MySQL power dynamic web applications like blogs, forums, and e-commerce stores.

This chapter covers:

  • Setting up a MySQL database
  • Connecting PHP to MySQL using mysqli
  • Performing CRUD operations (Create, Read, Update, Delete)
  • Using prepared statements to prevent SQL injection

🔹 2. Setting Up MySQL

Most local servers (XAMPP, MAMP, Laragon) include phpMyAdmin, a graphical tool to manage MySQL.

Steps:

  1. Go to http://localhost/phpmyadmin
  2. Create a new database (e.g. myapp)
  3. Create a table called users:

Column

Type

Length

Attributes

id

INT

11

AUTO_INCREMENT (PK)

name

VARCHAR

100


email

VARCHAR

100



🔹 3. Connecting PHP to MySQL

Using mysqli:

$host = "localhost";

$user = "root";

$pass = "";

$db = "myapp";

 

$conn = mysqli_connect($host, $user, $pass, $db);

 

if (!$conn) {

  die("Connection failed: " . mysqli_connect_error());

}

echo "Connected successfully!";

Use this connection on top of every page that needs to interact with the database.


🔹 4. Inserting Data into MySQL

$name = "Alice";

$email = "alice@example.com";

 

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";

 

if (mysqli_query($conn, $sql)) {

  echo "New user added!";

} else {

  echo "Error: " . mysqli_error($conn);

}

️ This is vulnerable to SQL injection — better use prepared statements (see below).


🔹 5. Reading (SELECT) Data

$sql = "SELECT * FROM users";

$result = mysqli_query($conn, $sql);

 

while ($row = mysqli_fetch_assoc($result)) {

  echo "Name: " . $row["name"] . ", Email: " . $row["email"] . "<br>";

}


🔹 6. Updating Records

$sql = "UPDATE users SET name='Bob' WHERE id=1";

 

if (mysqli_query($conn, $sql)) {

  echo "Record updated successfully";

}


🔹 7. Deleting Records

$sql = "DELETE FROM users WHERE id=2";

 

if (mysqli_query($conn, $sql)) {

  echo "User deleted!";

}


🔹 8. Prepared Statements (Secure Way)

Inserting Securely:

$stmt = mysqli_prepare($conn, "INSERT INTO users (name, email) VALUES (?, ?)");

mysqli_stmt_bind_param($stmt, "ss", $name, $email);

 

$name = "John";

$email = "john@gmail.com";

mysqli_stmt_execute($stmt);

Use prepared statements to avoid SQL injection.


🔹 9. Displaying Data in a Table

echo "<table border='1'>";

echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";

 

$result = mysqli_query($conn, "SELECT * FROM users");

 

while($row = mysqli_fetch_assoc($result)){

  echo "<tr>

          <td>{$row['id']}</td>

          <td>{$row['name']}</td>

          <td>{$row['email']}</td>

        </tr>";

}

echo "</table>";


🔹 10. Closing the Connection

mysqli_close($conn);

Always close connections when you're done — this helps optimize resources.


Summary Table: MySQL Functions


Task

Function/Statement

Connect to MySQL

mysqli_connect()

Insert

INSERT INTO

Select

SELECT * FROM table

Update

UPDATE table SET column=value

Delete

DELETE FROM table WHERE id=...

Prepared Statements

mysqli_prepare() + bind_param()

Fetch Data

mysqli_fetch_assoc()

Close Connection

mysqli_close()

Back

FAQs


1. What is PHP used for?

PHP is primarily used for creating dynamic web pages and server-side applications such as login systems, e-commerce platforms, and CMSs.

2. Is PHP still relevant in 2025?

Absolutely. PHP continues to power most of the web and is essential in WordPress, Laravel, and web hosting environments.

3. Do I need to install anything to run PHP?

Yes — you can install XAMPP, MAMP, Laragon, or PHP CLI for local development.

4. What databases work with PHP?

MySQL is the most commonly used with PHP, but it also supports PostgreSQL, SQLite, and others.

5. What’s the difference between PHP and JavaScript?

PHP is a server-side scripting language, while JavaScript is primarily client-side, running in the browser.

6. Can I use PHP with HTML?

Yes PHP is often embedded inside HTML to create dynamic pages

7. What is a PHP file extension?

PHP files have the .php extension and are executed on the server.

8. How do I send data from a form to PHP?

Use method="POST" or method="GET" in your form and access data in PHP using $_POST or $_GET.

9. Is PHP good for building APIs?

Yes — PHP can be used to build RESTful APIs, especially with frameworks like Laravel or Slim.

10. What are some popular PHP frameworks?

Laravel, Symfony, CodeIgniter, Zend, and Slim are among the most used PHP frameworks.