When working with databases in PHP, PDO (PHP Data Objects) serves as a powerful and secure abstraction layer. The PDOStatement::fetch() method is a commonly used approach to retrieve a single record from the query result. This article provides a detailed explanation on how to efficiently use the fetch() function to obtain a single query result, including steps and example code to help you get started and avoid common mistakes.
PDOStatement::fetch() is a method used after executing a PDO prepared statement to fetch the next row from the result set. It returns a record as an array or object, depending on the specified fetch mode. Each call to fetch() moves the cursor one row forward in the result set.
First, you need to create a database connection instance using PDO.
<?php
$dsn = 'mysql:host=m66.net;dbname=testdb;charset=utf8mb4';
$username = 'your_username';
$password = 'your_password';
<p>try {<br>
$pdo = new PDO($dsn, $username, $password);<br>
// Set error mode to exception<br>
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);<br>
} catch (PDOException $e) {<br>
die("Database connection failed: " . $e->getMessage());<br>
}<br>
?><br>
Use a prepared statement to write and execute your SQL query.
<?php
$sql = "SELECT id, name, email FROM users WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => 1]);
?>
Use fetch() to retrieve one record. Common return types include:
PDO::FETCH_ASSOC: Returns an associative array
PDO::FETCH_OBJ: Returns an object
Example:
<?php
// Retrieve as associative array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
<p>if ($row) {<br>
echo "User ID: " . $row['id'] . "\n";<br>
echo "Username: " . $row['name'] . "\n";<br>
echo "Email: " . $row['email'] . "\n";<br>
} else {<br>
echo "No matching record found.";<br>
}<br>
?><br>
Fetch only a single result: fetch() returns just one row, which is ideal for primary key lookups or when only one record is needed, preventing resource waste compared to fetchAll().
Bind parameters: Use prepared statements with parameter binding to prevent SQL injection and improve execution efficiency.
Choose the appropriate fetch mode: PDO::FETCH_ASSOC is generally recommended as it conserves memory and allows convenient access via column names.
<?php
$dsn = 'mysql:host=m66.net;dbname=testdb;charset=utf8mb4';
$username = 'your_username';
$password = 'your_password';
<p>try {<br>
$pdo = new PDO($dsn, $username, $password);<br>
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);</p>
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => 1]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
echo "User ID: " . $user['id'] . "\n";
echo "Username: " . $user['name'] . "\n";
echo "Email: " . $user['email'] . "\n";
} else {
echo "User not found.";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
Related Tags:
PDOStatement