Welcome to our PHP PDO fetch() tutorial! This lesson is designed for both beginners and intermediates, so let's get started.
PDO (PHP Data Objects) is a PHP extension that provides a uniform PHP interface for accessing various database systems. It helps in writing database-independent code.
fetch() is a method used to fetch a single row from a database. It's part of the PDOStatement interface, and it returns an associative array representing the row.
Let's create a simple example to understand the fetch() method better.
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
$stmt = $pdo->query("SELECT id, name FROM users");
while ($row = $stmt->fetch()) {
echo $row['id'] . ": " . $row['name'] . "\n";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>In this example, we're connecting to a MySQL database, executing a SELECT query, and fetching each row until there are no more rows left.
Now, let's consider a more practical scenario where we fetch data using a prepared statement. This helps to prevent SQL injection attacks.
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE name = ?");
$stmt->execute(array('John'));
$row = $stmt->fetch();
echo $row['id'] . ": " . $row['name'] . "\n";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>In this example, we're preparing a statement with a placeholder (?), which will be replaced with the actual value ('John') when we execute the query.
fetch() supports different modes to control how the data is returned. Here are some common modes:
fetch(PDO::FETCH_ASSOC): Returns an associative array.fetch(PDO::FETCH_NUM): Returns a numeric array.fetch(PDO::FETCH_BOTH): Returns an associative array with numeric keys.What does the `fetch()` method in PHP PDO do?
That's it for this PHP PDO fetch() tutorial! We hope you found it helpful and engaging. As always, if you have any questions or need further clarification, feel free to ask. Happy coding! π‘