How can the PHP code be optimized to improve performance when handling multiple SQL queries in functions within a web application?
To optimize PHP code for handling multiple SQL queries in functions within a web application, you can utilize prepared statements to reduce database load and improve performance. Prepared statements can be used to execute multiple queries efficiently without the need to recompile the SQL query each time. By binding parameters to the prepared statement, you can prevent SQL injection attacks and enhance security.
// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare the SQL query
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
// Bind parameters
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Close the connection
$pdo = null;