What are common errors to look out for when writing PHP scripts that interact with a MySQL database?

One common error to look out for when writing PHP scripts that interact with a MySQL database is not properly sanitizing user input, which can lead to SQL injection attacks. To solve this issue, always use prepared statements or parameterized queries to prevent malicious SQL queries from being executed.

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Sanitize user input using prepared statements
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

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

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

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

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