What are common pitfalls when using PHP to interact with a database, as seen in the provided script?

One common pitfall when using PHP to interact with a 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 securely pass user input to the database.

// Original script with SQL injection vulnerability
$username = $_POST['username'];
$password = $_POST['password'];

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);

// Fixed script using prepared statements
$username = $_POST['username'];
$password = $_POST['password'];

$query = "SELECT * FROM users WHERE username=? AND password=?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);