How can PHP ensure proper character encoding when passing data to SQL queries?

Improper character encoding can lead to SQL injection attacks or data corruption when passing data to SQL queries in PHP. To ensure proper character encoding, developers should use parameterized queries with prepared statements and bind parameters to avoid directly inserting user input into SQL queries.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");

// Bind parameters with proper character encoding
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);

// Set the values of the parameters
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

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