Part 13 : PHP tutorial for kids and beginners


Part 13: Working with Databases in PHP

Welcome back to our PHP programming tutorial series! 🎉 In Part 12, we explored Object-Oriented Programming (OOP) in PHP, covering classes, objects, inheritance, and other OOP concepts. Today, in Part 13, we’re diving into Working with Databases in PHP. We’ll learn how to connect to a database, perform CRUD operations, and use PDO for secure database interactions. Let’s get started!

Introduction to Databases

A database is a structured collection of data that can be accessed, managed, and updated efficiently. In web development, databases are used to store user data, manage application content, and more. PHP can interact with databases to create, read, update, and delete data—these are known as CRUD operations.

1. Introduction to MySQL and PDO

In this tutorial, we will use MySQL as our database management system and PDO (PHP Data Objects) for database interactions. PDO is a database access layer that provides a consistent API for working with different databases.

Setting Up MySQL

  1. Install MySQL: Download and install MySQL from the official website.
  2. Create a Database: Use the MySQL command line or a GUI tool like phpMyAdmin to create a new database.
   CREATE DATABASE my_database;
  1. Create a Table: Define a table structure to store data.
   USE my_database;

   CREATE TABLE users (
       id INT AUTO_INCREMENT PRIMARY KEY,
       name VARCHAR(100) NOT NULL,
       email VARCHAR(100) UNIQUE NOT NULL,
       password VARCHAR(255) NOT NULL
   );

2. Connecting to a Database with PDO

PDO provides a robust and secure way to interact with a MySQL database.

See also  How to Deploy Locally Developed Laravel Projects to AWS: A Step-by-Step Guide

Basic PDO Connection

Here’s how to connect to a MySQL database using PDO:

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully!";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

In this example:

  • new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password') creates a new PDO instance.
  • setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION) sets the error mode to throw exceptions.

3. Performing CRUD Operations

CRUD stands for Create, Read, Update, Delete—the four basic operations for managing database records.

Creating Records (Insert)

Here’s how to insert a new record into the users table:

<?php
$sql = "INSERT INTO users (name, email, password) VALUES (:name, :email, :password)";
$stmt = $pdo->prepare($sql);

$name = 'John Doe';
$email = '[email protected]';
$password = password_hash('password123', PASSWORD_DEFAULT);

$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);

$stmt->execute();
echo "New record created successfully!";
?>

In this example:

  • password_hash() creates a secure hash of the password.
  • bindParam() binds parameters to the SQL query.

Reading Records (Select)

Here’s how to read records from the users table:

<?php
$sql = "SELECT * FROM users";
$stmt = $pdo->query($sql);

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['name'] . " - " . $row['email'] . "<br>";
}
?>

In this example:

  • query() executes the SQL query.
  • fetch(PDO::FETCH_ASSOC) fetches records as an associative array.

Updating Records

Here’s how to update a record in the users table:

<?php
$sql = "UPDATE users SET name = :name WHERE email = :email";
$stmt = $pdo->prepare($sql);

$newName = 'Jane Doe';
$email = '[email protected]';

$stmt->bindParam(':name', $newName);
$stmt->bindParam(':email', $email);

$stmt->execute();
echo "Record updated successfully!";
?>

In this example:

  • prepare() prepares the SQL statement.
  • execute() executes the prepared statement.

Deleting Records

Here’s how to delete a record from the users table:

<?php
$sql = "DELETE FROM users WHERE email = :email";
$stmt = $pdo->prepare($sql);

$email = '[email protected]';

$stmt->bindParam(':email', $email);
$stmt->execute();
echo "Record deleted successfully!";
?>

In this example:

  • DELETE FROM users WHERE email = :email deletes records matching the specified email.

4. Using Prepared Statements for Security

Prepared Statements are crucial for preventing SQL Injection attacks. They separate SQL logic from data.

See also  Security Considerations in Migrations

Example of a Secure Query

<?php
$sql = "SELECT * FROM users WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':email', $email);
$email = '[email protected]';
$stmt->execute();
?>

In this example:

  • Prepared statements ensure that user input is handled safely.

5. Handling Exceptions and Errors

PDO allows you to handle exceptions and errors effectively.

Example of Exception Handling

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

In this example:

  • Exceptions are caught and an error message is displayed.

6. Advanced PDO Features

PDO offers advanced features for more complex scenarios.

Transactions

Transactions allow you to execute multiple queries as a single unit of work:

<?php
try {
    $pdo->beginTransaction();

    $pdo->exec("INSERT INTO users (name, email, password) VALUES ('Alice', '[email protected]', 'password123')");
    $pdo->exec("INSERT INTO users (name, email, password) VALUES ('Bob', '[email protected]', 'password123')");

    $pdo->commit();
    echo "Transaction successful!";
} catch (Exception $e) {
    $pdo->rollBack();
    echo "Failed: " . $e->getMessage();
}
?>

Prepared Statements with Multiple Parameters

<?php
$sql = "INSERT INTO users (name, email, password) VALUES (:name, :email, :password)";
$stmt = $pdo->prepare($sql);

$stmt->execute([
    ':name' => 'Charlie',
    ':email' => '[email protected]',
    ':password' => password_hash('password456', PASSWORD_DEFAULT),
]);
echo "New record created successfully!";
?>

7. Real-World Example: Building a Simple User Registration System

Let’s build a simple user registration system to put our knowledge into practice.

register.php

<?php
require 'config.php'; // Contains the PDO connection setup

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $sql = "INSERT INTO users (name, email, password) VALUES (:name, :email, :password)";
    $stmt = $pdo->prepare($sql);

    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':password', $password);

    if ($stmt->execute()) {
        echo "User registered successfully!";
    } else {
        echo "Registration failed!";
    }
}
?>

<form method="POST" action="register.php">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required><br>
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required><br>
    <button type="submit">Register</button>
</form>

config.php

<?php
$dsn = 'mysql:host=localhost;dbname=my_database';
$username = 'root';
$password = '';

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

8. Best Practices for Database Interactions

Here are some best practices for working with databases in PHP:

  • Use Prepared Statements: Always use prepared statements to prevent SQL Injection attacks.
  • Validate User Input: Validate and sanitize user inputs before processing.
  • Handle Exceptions: Use try-catch blocks to manage database errors and exceptions.
  • Secure Passwords: Hash passwords using password_hash() and verify with password_verify().
  • Optimize Queries: Use indexes and optimize queries for better performance.
  • Use Transactions: Manage complex operations with transactions to ensure data integrity.
See also  Understanding PHP Laravel Database Migration Commands

Summary

In Part 13, we explored Working with Databases in PHP. We learned how to connect to a MySQL database using PDO, perform CRUD operations, handle exceptions, and use advanced features like transactions. We also built a simple user registration system to apply what we’ve learned.

What’s Next?

In Part 14, we will explore Creating and Using PHP Forms. We’ll learn about form elements, form validation, and handling form submissions.

Homework

  1. Create a PHP Form: Design a form with various input fields and process the form data using PHP.
  2. Implement CRUD Operations: Create a PHP script to perform CRUD operations on a database table.
  3. Practice Using PDO: Write a script that connects to a database, inserts data, and retrieves records.

Feel free to leave comments if you have any questions or run into any issues. Happy coding! 🚀


Next Part Teaser

Stay tuned for Part 14: Creating and Using PHP Forms, where we will explore form elements, validation, and handling form submissions!

Additional Resources

If you want to explore more about working with databases in PHP, check out these resources:


Part 14 Teaser

Coming up next in Part 14: Creating and Using PHP Forms, where we will explore form elements, validation, and handling form submissions!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.