47. CRUD Operations with PDO: Selecting and Fetching Data
'Read' operations retrieve data from the database using the SQL SELECT command.
1. Simple Selection (Fetching All)
We still use prepared statements, even when the query doesn't require user input, for consistency and security.
php
prepare($sql); $stmt->execute(); // Fetching all rows into a PHP array $users = $stmt->fetchAll(PDO::FETCH_ASSOC); if ($users) { echo "User List:
"; foreach ($users as $user) { echo "ID: " . $user['id'] . ", Name: " . $user['username'] . ""; } } else { echo "No users found."; } ?>
PDO Fetch Modes:
PDO::FETCH_ASSOC: Returns results as an associative array (key is the column name). (Most common)PDO::FETCH_NUM: Returns results as an indexed array (key is the column index).PDO::FETCH_OBJ: Returns results as a generic PHP object.
2. Selecting Specific Records
We use the WHERE clause and binding to retrieve data based on criteria, typically an ID.
php
prepare($sql); $stmt->bindParam(':id', $target_id, PDO::PARAM_INT); $stmt->execute(); // Use fetch() for a single row $user = $stmt->fetch(PDO::FETCH_ASSOC); if ($user) { echo "Details for ID 2: " . $user['email']; } ?>