What potential pitfalls should be considered when working with arrays in PHP, especially when fetching data from a database?
When working with arrays in PHP, especially when fetching data from a database, potential pitfalls to consider include ensuring proper error handling for database queries, avoiding SQL injection attacks by using prepared statements, and properly sanitizing and validating user input to prevent malicious data manipulation.
// Example code snippet for fetching data from a database using prepared statements
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
// Bind parameters and execute the statement
$id = 1;
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
// Fetch the results as an associative array
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// Handle any errors
if (!$user) {
echo "User not found";
} else {
// Process the retrieved data
// ...
}