How can one ensure that variables passed into SQL queries in PHP do not contain invalid characters or formatting that may cause errors?

To ensure that variables passed into SQL queries in PHP do not contain invalid characters or formatting that may cause errors, it is important to use prepared statements with parameterized queries. This helps prevent SQL injection attacks and ensures that the variables are properly sanitized before being executed in the database query.

// Example of using prepared statements with parameterized queries to prevent SQL injection

// Assuming $conn is the database connection object

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

$username = $_POST['username']; // Assuming this is the user input

$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // Process the retrieved data
}

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