New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› MySQL› Reading and Writing Data

Reading and Writing Data

💻 MySQL

Use SELECT, INSERT, UPDATE and DELETE from applications and the command line.

Lesson 4 of 9 Tutorial
0 of 9 completed

Most application queries are simple reads and writes. Doing them safely is the difference between a stable app and a data incident.

By the end of this lesson you can:
  • Insert with prepared statements.
  • Read one row and many rows.
  • Update and delete safely.

Insert from PHP

Use prepared statements and named parameters. Never build SQL by joining strings with user input.

<?php

$stmt = $pdo->prepare(
    'INSERT INTO students (name, email) VALUES (:name, :email)'
);
$stmt->execute([
    'name' => $name,
    'email' => $email,
]);

$id = (int)$pdo->lastInsertId();

Read from PHP

fetch returns one row, fetchAll returns all rows. Use LIMIT when you only need a few.

<?php

$stmt = $pdo->prepare('SELECT id, name FROM students WHERE level = :level');
$stmt->execute(['level' => 'SS2']);

$students = $stmt->fetchAll();

foreach ($students as $student) {
    echo htmlspecialchars($student['name']);
}

Update and Delete

Check rowCount() to confirm something actually changed. A zero means no row matched your condition.

<?php

$stmt = $pdo->prepare('UPDATE students SET level = :level WHERE id = :id');
$stmt->execute(['level' => 'SS3', 'id' => 7]);

if ($stmt->rowCount() === 0) {
    echo 'No student was updated.';
}
Tip Use LIMIT 1 when you expect one row. It prevents an accidental full scan from returning a huge list.

Practice

  1. Insert a new course with a prepared statement.
  2. Fetch all students in SS1 sorted by name.
  3. Delete a course by id and check rowCount.

Hands-on exercise

Write PHP that:
1. Inserts a student with a prepared statement.
2. Gets the new id with lastInsertId().
3. Fetches that student and prints the name.

Recap

Prepared statements protect every write. fetch returns one row, fetchAll returns many, and rowCount confirms the change.

Example

<?php

$stmt = $pdo->prepare(
    'INSERT INTO students (name, email) VALUES (:name, :email)'
);
$stmt->execute([
    'name' => $name,
    'email' => $email,
]);

$id = (int)$pdo->lastInsertId();

Exercises

Exercise 1. Create and read Medium
Write PHP that:
1. Inserts a student with a prepared statement.
2. Gets the new id with lastInsertId().
3. Fetches that student and prints the name.
MySQL exercise-1.txt
Expected Output
Ada Obi

Lesson Nav

Lesson sections