What are the best practices for handling database queries in PHP to ensure efficient and accurate results?

When handling database queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and improve performance. Additionally, utilizing indexes on frequently queried columns can help optimize query execution. It is also recommended to limit the amount of data retrieved by using SELECT statements with specific columns rather than selecting all data.

// Example of using prepared statements in PHP to handle database queries
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Prepare a SQL statement
$stmt = $conn->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->bind_param("i", $id);

// Set parameters and execute
$id = 1;
$stmt->execute();

// Bind result variables
$stmt->bind_result($userId, $userName);

// Fetch results
while ($stmt->fetch()) {
    echo "ID: " . $userId . " Name: " . $userName . "<br>";
}

// Close statement and connection
$stmt->close();
$conn->close();