简体   繁体   中英

Should I set Content-Type header twice in PHP?

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', 'dennis@example.com')";
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM