charset issues in printing text from db table

2019-07-28 01:02发布

问题:

I have a database defined with charset utf8_general_ci and a table that should store some text inserted from a text area form with the same charset.

The form I use to get the text is this:

<form action="submit_text.php" method="post">

    Text:</br>
    <textarea name="text" cols="109" rows="20">
        <?php echohtmlspecialchars($_POST['text']);?>
    </textarea>

    <input name="submit" type="submit" value="save text">

</form>

The php instructions I use to save this text in my database are the following:

$text = $_POST['text'];
$query = "INSERT INTO table_name VALUES (..., '$text', ...)";
$query_result = mysql_query($query) or die (mysql_error());
return $query_result;

I then have a page where I print the text saved in the database table by selecting one element of the table and then echoing the text field of the query result (not showing the query part):

<div class="entry">
    <?php echo $selected_element_of_table['text'];?>
</div>

However, all special characters in the text are screwed up, and neither newlines or tabs are printed correctly.

Does anybody have an idea of what my problem is? Should I change charset encoding?

Thanks in advance!

回答1:

A few things to try:

In pages that will display UTF-8 content, in your header include:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

In your PHP, before any output to the browser, include the content type PHP header:

header ('Content-type: text/html; charset=utf-8');

Before you run your SQL to fetch content, use mysql_set_charset:

mysql_set_charset('utf8',$link); 
// $link is optional, refers to your DB connection

If you wish breaks/carriage returns to be output, wrap your output text in nl2br($output)