Lesson 27 of 32Article19 min
MySQL — Select, Where & Order By
SELECT chooses columns FROM a table. fetch() gets one row; fetchAll() gets every row as an array.
Select Data
SELECT chooses columns FROM a table. fetch() gets one row; fetchAll() gets every row as an array.
Real-life example: SELECT is searching a library catalog — you pick which book details to see.
SELECT and fetchAll
<?php
$stmt = $pdo->query("SELECT id, name, score FROM students");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
echo $row["name"] . ": " . $row["score"] . "\n";
}
?>SQL SELECT
SELECT id, name, email, score FROM students;
SELECT name FROM students WHERE score >= 80;Where Clause
WHERE filters rows. Use AND, OR, IN, LIKE, and BETWEEN. Always bind user values in prepared statements.
Real-life example: WHERE is a filter on a shopping site — show only shoes, size 9, under ₹2000.
WHERE with prepared params
<?php
$minScore = 80;
$stmt = $pdo->prepare("SELECT * FROM students WHERE score >= :min ORDER BY score DESC");
$stmt->execute([":min" => $minScore]);
$top = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>SQL WHERE examples
SELECT * FROM students WHERE name LIKE 'A%';
SELECT * FROM students WHERE score BETWEEN 70 AND 90;
SELECT * FROM students WHERE id IN (1, 3, 5);Order By
ORDER BY sorts results ASC (default) or DESC. Sort by one or more columns.
Real-life example: ORDER BY is sorting a playlist — by artist name A–Z or by date newest first.
ORDER BY
SELECT name, score FROM students
ORDER BY score DESC, name ASC;