PHP MySQLi: Database Connectivity, CRUD Operations & Prepared Statements

Dynamic websites thrive on databases. An e-commerce store needs to store products and process orders; a university portal needs to manage student grades and attendance. MySQLi (MySQL Improved) is a dedicated relational database driver built specifically for PHP to communicate with MySQL and MariaDB databases. It provides high execution speed, dual procedural and object-oriented syntax, and native support for Prepared Statements.

Establishing a Secure Connection: Object-Oriented MySQLi

<?php
    $host = "localhost";
    $user = "root";
    $password = "";
    $database = "veewom_academy";

    // Step 1: Create connection using the mysqli class
    $conn = new mysqli($host, $user, $password, $database);

    // Step 2: Check for connection errors
    if ($conn->connect_error) {
        die("Database Connection Failed: " . $conn->connect_error);
    }

    // Step 3: Set charset to utf8mb4 for complete Unicode/Emoji support
    $conn->set_charset("utf8mb4");

    echo "Connected successfully to MySQL database via MySQLi!";
?>

The Golden Rule: Preventing SQL Injection with Prepared Statements

Why Concatenating Variables into SQL is Fatal:

Writing "SELECT * FROM users WHERE user = '$username'" allows attackers to input ' OR '1'='1, bypassing authentication and dumping your entire database! Always use Prepared Statements.

Step-by-Step Prepared Statement CRUD: INSERT Record

<?php
    // The SQL statement template with placeholders (?)
    $sql = "INSERT INTO students (full_name, email, course, marks) VALUES (?, ?, ?, ?)";

    // 1. Prepare the query
    $stmt = $conn->prepare($sql);

    // 2. Bind parameters (s = string, i = integer, d = double/float, b = blob)
    $name = "Arjun Kapoor";
    $email = "arjun@example.com";
    $course = "BCA";
    $marks = 92.5;

    $stmt->bind_param("sssd", $name, $email, $course, $marks);

    // 3. Execute
    if ($stmt->execute()) {
        echo "New student record inserted with ID: " . $stmt->insert_id;
    } else {
        echo "Execute failed: " . $stmt->error;
    }

    $stmt->close();
?>

Reading Records with Prepared Statements (SELECT)

<?php
    $searchCourse = "BCA";

    $stmt = $conn->prepare("SELECT id, full_name, email, marks FROM students WHERE course = ?");
    $stmt->bind_param("s", $searchCourse);
    $stmt->execute();

    // Get the result set
    $result = $stmt->get_result();

    echo "<table border='1' cellpadding='6'>";
    echo "<tr><th>ID</th><th>Name</th><th>Email</th><th>Marks</th></tr>";

    while ($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . htmlspecialchars($row['full_name']) . "</td>";
        echo "<td>" . htmlspecialchars($row['email']) . "</td>";
        echo "<td>" . $row['marks'] . "%</td>";
        echo "</tr>";
    }
    echo "</table>";

    $stmt->close();
    $conn->close();
?>

BCA / CS University Exam Corner

High-Frequency Exam Question:

Q: What are the type definition letters in bind_param()?
A:
• i - corresponding variable has type integer
• d - corresponding variable has type double/float
• s - corresponding variable has type string
• b - corresponding variable is a blob and will be sent in packets.

Interactive Student Practice Session

Exercise 33.1: Write a complete MySQLi script that connects to your local database and performs an UPDATE operation on a student's marks using prepared statements.

Exercise 33.2: Write a script that performs a DELETE operation on a student record based on their ID, confirming the number of affected rows with $stmt->affected_rows.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!