What best practices should be followed when using MySQL queries in PHP?

When using MySQL queries in PHP, it is important to follow best practices to ensure security and efficiency. One key practice is to use prepared statements with parameterized queries to prevent SQL injection attacks. Additionally, always sanitize user input to prevent malicious code execution. Lastly, close database connections after use to free up resources.

// 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);
}

// Use prepared statements with parameterized queries
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Sanitize user input
$username = mysqli_real_escape_string($conn, $_POST['username']);

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

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