What best practices should be followed when dealing with MySQL queries in PHP code?

When dealing with MySQL queries in PHP code, it is important to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL logic from user input, making it safer to execute queries. Additionally, it is recommended to sanitize user input before using it in a query to further prevent security vulnerabilities.

// 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 statement with placeholders
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters to the placeholders
$stmt->bind_param("s", $username);

// Sanitize user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);

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

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

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

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