What potential pitfalls should be considered when reading data from a database into an array in PHP?
One potential pitfall when reading data from a database into an array in PHP is the risk of SQL injection attacks if the input data is not properly sanitized. To prevent this, always use prepared statements with parameterized queries to securely retrieve data from the database.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE id = :id");
// Bind the parameter value
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
// Execute the query
$stmt->execute();
// Fetch the result into an associative array
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// Use the data from the array
print_r($result);