I have a PHP script that inserts data into MySQL which has to be done using UTF-8.
If the action was successfully executed, I would like to echo "success" using JSON which is why I need to set the Content-Type header twice or am I wrong?
Example code:
<?php
header('Content-Type: text/html; charset=utf-8'); // header one
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Dennis', 'Enström', '[email protected]')";
if (mysqli_query($conn, $sql)) {
header('Content-Type: application/json'); // header two
echo json_encode('success');
}
Is this the correct way to do it or how should I do it?
UPDATE
The MySQL values comes from $_POST and the HTML document has UTF-8 set.
Use mysqli_set_charset()
(PHP manual page) to set the charset used by the Mysql client interface.
The use of header()
sends a header to the client's browser saying how to read your JSON encoded "success" string.
It may be a good idea at this point to validate the encoding selected in your database.
Note that your code is currently missing the command to open the mysqli connection before running the query.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments