What are the potential pitfalls of not encoding characters correctly in PHP for database interactions?

If characters are not encoded correctly in PHP for database interactions, it can lead to issues such as data corruption, SQL injection attacks, and incorrect data retrieval. To prevent these pitfalls, it is crucial to properly encode characters using functions like mysqli_real_escape_string() or prepared statements when interacting with a database in PHP.

// Using mysqli_real_escape_string to encode characters before inserting into the database
$connection = mysqli_connect("localhost", "username", "password", "database");
$name = mysqli_real_escape_string($connection, $name);
$email = mysqli_real_escape_string($connection, $email);

$query = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
mysqli_query($connection, $query);