What common mistakes can occur when using PHP and MySQL together?

One common mistake when using PHP and MySQL together is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements or parameterized queries when interacting with the database. Another mistake is not handling database connection errors gracefully, which can result in insecure error messages being displayed to users. Always use error handling techniques to catch and handle any database connection errors.

// Correct way to use prepared statements for MySQL queries in PHP
$mysqli = new mysqli("localhost", "username", "password", "database");

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

$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = "example_user";
$stmt->execute();

$result = $stmt->get_result();

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

$stmt->close();
$mysqli->close();