How can the use of $_POST['username'] and $_POST['password'] in PHP scripts lead to errors in MySQL queries?

Using $_POST['username'] and $_POST['password'] directly in MySQL queries can lead to SQL injection vulnerabilities if the input is not properly sanitized. To prevent this, you should use prepared statements with placeholders to safely insert user input into the query.

// Establish database connection
$connection = new mysqli('localhost', 'username', 'password', 'database');

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

// Prepare SQL statement with placeholders
$stmt = $connection->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $_POST['username'], $_POST['password']);

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

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

// Process results as needed

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