What potential pitfalls should be considered when populating an array from a database in PHP?
One potential pitfall when populating an array from a database in PHP is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, always use prepared statements or parameterized queries to interact with the database. Additionally, be cautious of the amount of data being retrieved from the database to avoid memory issues.
// Example of using prepared statements to populate an array from a database in PHP
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a statement
$stmt = $pdo->prepare("SELECT * FROM mytable");
// Execute the statement
$stmt->execute();
// Fetch the results into an array
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through the array and do something with the data
foreach($results as $row) {
// Do something with $row
}