What are best practices for handling MySQL queries in PHP to avoid returning false results?

When handling MySQL queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, always check for errors after executing a query to avoid returning false results due to syntax errors or connection issues.

// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Prepare a SQL query using a prepared statement
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $value);

// Execute the query
$stmt->execute();

// Check for query execution errors
if ($stmt->error) {
    die("Query failed: " . $stmt->error);
}

// Fetch the results
$result = $stmt->get_result();

// Process the results
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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