What are some best practices for reading arrays from a table in PHP?
When reading arrays from a table in PHP, it is best practice to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, fetching the data using a loop and storing it in an array allows for easier manipulation and processing of the data.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// Prepare a statement to select data from the table
$stmt = $pdo->prepare("SELECT * FROM table_name");
// Execute the statement
$stmt->execute();
// Fetch data and store it in an array
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
// Use the data array for further processing
foreach ($data as $row) {
// Do something with each row of data
}