Reading and Writing Data
💻 MySQLUse SELECT, INSERT, UPDATE and DELETE from applications and the command line.
Most application queries are simple reads and writes. Doing them safely is the difference between a stable app and a data incident.
- 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.';
}Practice
- Insert a new course with a prepared statement.
- Fetch all students in SS1 sorted by name.
- 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
1. Inserts a student with a prepared statement.
2. Gets the new id with lastInsertId().
3. Fetches that student and prints the name.
Expected Output
Ada Obi
Lesson Nav
MySQL Course
0/9 lessons completed
- 1 Connecting to MySQL Tutorial
- 2 Creating Databases and Tables Tutorial
- 3 Data Types and Constraints Tutorial
- 4 Reading and Writing Data Tutorial
- 5 Joins and Relationships in MySQL Tutorial
- 6 Functions, Dates and Text Tutorial
- 7 Views and Stored Procedures Tutorial
- 8 Users, Permissions and Backups Tutorial
- 9 Project: A Small School Database Project