What are the potential risks of not properly handling character encoding when processing form data in PHP before inserting it into a MySQL database?
Improper handling of character encoding when processing form data in PHP before inserting it into a MySQL database can lead to data corruption or security vulnerabilities. To prevent this, it is important to properly sanitize and validate input data, as well as set the correct character encoding for both the PHP script and the MySQL connection.
// Set the character encoding for the PHP script
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding('UTF-8');
// Set the character encoding for the MySQL connection
$mysqli->set_charset('utf8');
// Sanitize and validate form data before inserting into the database
$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// Insert sanitized data into the database
$query = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
$mysqli->query($query);