What are some best practices for structuring PHP code to handle database queries and result processing efficiently?
When handling database queries in PHP, it's important to structure your code efficiently to ensure optimal performance. One best practice is to separate your database logic from your presentation logic by using functions or classes to handle queries and result processing. This helps to keep your code organized and maintainable. Additionally, consider using prepared statements to prevent SQL injection attacks and improve query performance.
// Example of structuring PHP code for handling database queries efficiently
// Function to connect to the database
function connectToDatabase() {
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
return $db;
}
// Function to execute a query and return the result
function executeQuery($query) {
$db = connectToDatabase();
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
// Example usage
$query = "SELECT * FROM users";
$users = executeQuery($query);
foreach ($users as $user) {
echo $user['name'] . "<br>";
}