What are the best practices for structuring PHP code to handle multiple database queries in a single script?

When handling multiple database queries in a single PHP script, it is important to establish a connection to the database once and reuse that connection throughout the script to improve performance and efficiency. Additionally, using prepared statements can help prevent SQL injection attacks and improve security. Finally, organizing the queries into separate functions or sections can make the code more readable and maintainable.

<?php

// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query 1
$query1 = "SELECT * FROM table1";
$result1 = $conn->query($query1);

// Query 2
$query2 = "SELECT * FROM table2";
$result2 = $conn->query($query2);

// Close the connection
$conn->close();

?>