How can PHP beginners avoid common errors when querying a database using mysqli?

Beginners can avoid common errors when querying a database using mysqli by ensuring they properly handle errors, sanitize user input to prevent SQL injection attacks, and use prepared statements to execute queries safely.

<?php
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Sanitize user input
$user_input = $mysqli->real_escape_string($_POST['user_input']);

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

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

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