New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming PHP PHP and MySQL Database

PHP and MySQL Database

🐘 PHP

Connect to MySQL and perform CRUD operations.

Lesson 4 of 5 Tutorial
0/5 completed

PHP and MySQL

Connection (PDO)

<?php
$dsn = "mysql:host=localhost;dbname=school;charset=utf8mb4";
$pdo = new PDO($dsn, "root", "", [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
?>

CRUD Operations

// CREATE
$stmt = $pdo->prepare("INSERT INTO students (name, grade) VALUES (?, ?)");
$stmt->execute(["Alice", 85]);

// READ
$students = $pdo->query("SELECT * FROM students")->fetchAll();

// UPDATE
$stmt = $pdo->prepare("UPDATE students SET grade = ? WHERE name = ?");
$stmt->execute([90, "Alice"]);

// DELETE
$stmt = $pdo->prepare("DELETE FROM students WHERE name = ?");
$stmt->execute(["Alice"]);
?>
📌 Always use prepared statements!

They prevent SQL injection attacks. Never put user input directly in SQL queries.

Example

<?php
// Database CRUD Example
$dsn = "mysql:host=localhost;dbname=test;charset=utf8mb4";
try {
    $pdo = new PDO($dsn, "root", "", [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);

    // Create table
    $pdo->exec("CREATE TABLE IF NOT EXISTS students (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100),
        grade INT
    )");

    // Insert
    $stmt = $pdo->prepare("INSERT INTO students (name, grade) VALUES (?, ?)");
    $stmt->execute(["Amina", 92]);
    $stmt->execute(["Ibrahim", 85]);
    $stmt->execute(["Chioma", 78]);

    // Read
    $students = $pdo->query("SELECT * FROM students")->fetchAll();
    foreach ($students as $s) {
        echo "{$s['name']} - Grade: {$s['grade']}
";
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

Lesson Nav

Lesson sections