How can special characters like ' and " in user input be handled in PHP to prevent errors when inserting into a database?

Special characters like ' and " in user input can cause SQL injection vulnerabilities when inserted into a database. To prevent errors, these special characters should be properly escaped before inserting into the database. This can be done using PHP's mysqli_real_escape_string() function or prepared statements.

// Assuming $conn is the mysqli connection object
$user_input = $_POST['user_input'];
$escaped_input = mysqli_real_escape_string($conn, $user_input);

// Insert the escaped input into the database
$query = "INSERT INTO table_name (column_name) VALUES ('$escaped_input')";
mysqli_query($conn, $query);