How can PHP developers simplify and optimize their code for database query result storage?
PHP developers can simplify and optimize their code for database query result storage by using associative arrays to store the results. This allows for easy access to specific columns by using the column names as keys. Additionally, developers can use prepared statements to prevent SQL injection attacks and improve performance.
// Example of storing database query results in an associative array
$query = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
// Accessing specific columns from the result
foreach ($data as $user) {
echo $user['id'] . " - " . $user['name'] . " - " . $user['email'] . "<br>";
}