<?php
require ('sql_connect.php');
$query = "select * from `products`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$imagem = $row['imagem'];
$texto = $row['texto'];
echo "<img src=Images/Products/$imagem> <br> $texto";
}
?>
I have the image and the text of the image that i want to show in my database.
I show the image but i have problems with the text... The text dont show the enters/spaces and the accents.
Image of problem: http://imgur.com/LHg4eK6,C7SZD4M
I want this: http://imgur.com/LHg4eK6,C7SZD4M#1
This is happening because you didn't properly set the encoding to UTF-8 (or another one that contains all characters you want to display). To do this, you need to:
Set the encoding to UTF-8 in the database itself (you can skip this step if you can see the text properly in PhpMyAdmin).
Tell PHP that you're using UTF-8. To do this, run:
mysql_query("SET NAMES utf8");
right after you connect to the database (add this line to the end of your sql_connect.php file).
Please note that you shouldn't use mysql_* functions anymore (see my comment on your question). If you switch to MySQLi, you can run this:
$db->set_charset("utf-8");
to change the charset.
See also:
UTF-8 all the way through
How can I prevent SQL-injection in PHP?
Related
I am storing an emoji as part of a string in a text field in MySQL:
<div><span id="emoji_1f600">😀</span></div>
The field in MySQL has utf8_general_ci set. When the data is stored into MySQL the field, the data now looks like this:
<div><span id="emoji_1f600">😀</span></div>
I am assuming that is because of how the emoji is stored. Please educate me if I am wrong on this point, as I thought I would have seen the unicode of 😀 instead of the strange characters.
I then fetch the data from the MySQL field into a php var and do a substring to get just the actual emoji between the span tags. The value in the php var now looks like this:
"C0E8Kb,"
My code makes an attempt to get the unicode back by doing the following:
$code = utf8_encode($code) //$code contains the string "C0E8KB,"
The result is "CB0CB8CBC"BB,"
I am obviously not handling the emoji utf8 code properly and welcome any and all help and instruction.
Thanks in advance.
I don't really need UTF8 all the way through. Just on one field. Which the field in MySOL is typed to be utf8.
Ok I made a major mistake in my problem description. It is true that my code is producing the following html
<div><span id="emoji_1f600">😀</span></div>
However, this html is within an editor from a 3rd party and the emoji code within my span tag is actually being rendered as an emoji. So when I save the data from the editor, what I get back from the editor is the following:
<div>test 2 <span id="emoji_1f600">😀</span></div>
I am assuming the strange chars between the span tags is the actual emoji, since it is being rendered. Is this ok as is, or should I be replacing that with the actual 😀 code, prior to storing it in the database? My fear is that if I do that, then the actual emoji will not get rendered when I place the string from the database into an html string to be rendered.
Your problem is assuming that MySQL's characterset called utf8 is actually utf8. It isn't. MySQLs utf8 is a 3-bytes subset of utf8 that does not cover emojis. In order to tell MySQL to not corrupt your data in the future, and give an error instead when invalid characters are given for the row, enable the STRICT_TRANS_TABLES sql_mode. In order to make mysql use the real 4-byte utf8, make the row characterset "utf8mb4" - in short, mysqls utf8 is a retardedly named utf8 subset, and the real utf8 is called utf8mb4 in MySQL. (This is also true for MariaDB btw, which inherited this brain damage from the MySQL source code it was forked from)
utf8_encode should not be used as your DB is already UTF-8 ; it encodes from ISO-8859-1 (often found with MySQL) to UTF-8 ; it may produce bad chars if your data is already utf-8 encoded. Is the html page containing the data that you want to store declared as utf-8 ? Something like this :
<head>
<meta charset="UTF-8">
</head>
I was bored so I tried the following code with no issue :
`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div><span id="emoji_1f600">😀</span></div>
<?php
$mysqli=new mysqli("127.0.0.1", "root", "","utf8_general_mysql");
$num=1;
$text="😀";
$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?, ?)");
$stmt->bind_param('ds', $num, $text);
$stmt->execute();
echo '<div><span id="emoji_1f600">😀</span></div>';
$stmt = $mysqli->prepare("SELECT * FROM testtable WHERE testtable.text='😀'");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM))
{
foreach ($row as $r)
{
print "$r ";
}
print "\n";
}
?>
</body>
</html>`
Edit ... :
I really think it has to do with your headers content-type :
try to add :
header('Content-type: text/html; charset=utf-8');
then try
header('Content-type: text/html; charset=iso-8859-1'); (this is how you seem to be set)
on the page you are inserting data to MySQL, here are the 2 different rows :
I think meta charset does not work because http headers can be set elsewhere, these PHP lines should do the trick, hopefully.
To have these rows, i had to set the headers and replace the previous $text value with $text="😀" into my code sample.
I am reading a specific field from a database but I am having issues setting the correct charset, I still cant get the accents correctly (à, ã, ê, ...), it shows up as Chinese and question marks characters. is there something wrong in my php code? Thank you .
PHP
<?php
require 'functions.php';
require 'config.php';
$con = connect($config['DB_HOST'], $config['DB_USERNAME'], $config['DB_PASSWORD'],'data_db');
mysql_query("SET NAMES 'utf8'") OR die(mysql_error());
$sql_textIntro = "SELECT * FROM INTRO_TEXT";
$results_textIntro = mysql_query( $sql_textIntro, $con);
?>
HTML
<h1>TITLE</h1>
<?php
$record = mysql_fetch_array($results_textIntro);
echo "<p>".$record['TEXT_FIELD'].'</p>';
?>
</div>
Using mysql_set_charset is the right way to change the charset of the connection (not an SQL query).
You can do it this way:
mysql_set_charset('utf8', $link); //Take note that it's utf8 and NOT utf-8 here
You should also serve your webpage in UTF-8 and make sure your talble store strings in UTF-8 too.
Take note that functions mysql_* were deprecated in PHP 5.5.0, and were removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Try adding this as the first element inside the head tags:
<meta charset="utf-8">
Here is a very good, basic, read on character sets by Joel Spolsky in case you want to understand what is going on :)
(See the section under "There Ain't No Such Thing As Plain Text.")
in my.ini file must
character-set-server = utf8
if does not helps then see:
have set in html head encoding?
have apache set character set to utf8?
i have a database that contains both chinese characters and english. when i queried the database to display them on my browser using php, all i get for the chinese characters are gibberish, none readable characters.
what i have tried:
ini_set('mssql.charset', 'UTF-8')
on the client side i made sure i included the meta tag specifying UTF-8.
am using mssql server
language is php
any help will be great. thanks
I worked on a Chinese migration project last year and can point you at a few things to look at:
Check you are using NVARCHAR and NCHAR as your DB data types. Do not use VARCHAR/CHAR
I've not used PHP much, but in the majority of languages I've worked in, you need to make sure the appropriate locale is set/supported.
So a few things to check, try outputing some Chinese text on a sample .php file to confirm it is displaying as expected. Next, update your schema with the correct data types. Finally, point your test script at the DB to see if the data is displayed as expected.
Try setting the character set within the PHP file after you've connected. Then run the query.
<?php
include('db_access.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_set_charset($dbc, "utf8"); // Set the character set here!!
$query = "SELECT chinese FROM my_table";
while ($row = mysqli_fetch_array($query)) {
echo $row['chinese'].'<br />';
}
?>
PHP Manual: http://cn2.php.net/manual/zh/mysqli.set-charset.php
I am using a MySQL database to store some strings which contain German umlauts (äüö). The table "testtable" and the column "text" are utf8_bin collated, and PHPMyAdmin tells me the "MySQL connection" is also utf8_bin.
I then use a PHP script to read the strings and display them:
$sql = "SELECT `text` FROM `testtable` WHERE `id`=$id";
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, false);
mysql_select_db(MYSQL_DATABASE,$db);
$result = mysql_query($sql,$db);
if (!$result or mysql_errno()) die("Something was wrong with the query: $sql");
$rows = array();
while(($rows[] = mysql_fetch_assoc($result)) || array_pop($rows));
foreach ($rows as $r) {echo $r['text']}
The file itself is encoded in utf-8 according to my editor, and the page is declared as utf-8 in the head:
<meta charset="utf-8">
Yet, the text "This is a testmessage äüöß" in the database is displayed as "This is a testmessage ����". When I write umlauts directly into the HTML of the PHP file, or echo umlauts directly, they are displayed correctly, so I figure the encoding mistake must be somewhere between database and PHP server.
What factors that I've overlooked could be messing up the encoding here, or what could I try to figure out where exactly the problem lies?
PHPMyAdmin tells you only about its own connection charset and not about connection between database and your application. Try to run query
SET NAMES utf8
right after you made a connection
Only today I realized that I was missing this in my PHP scripts:
mysql_set_charset('utf8');
All my tables are InnoDB, collation "utf8_unicode_ci", and all my VARCHAR columns are "utf8_unicode_ci" as well. I have mb_internal_encoding('UTF-8'); on my PHP scripts, and all my PHP files are encoded as UTF-8.
So, until now, every time I "INSERT" something with diacritics, example:
mysql_query('INSERT INTO `table` SET `name`="Jáuò Iñe"');
The 'name' contents would be, in this case: Jáuò Iñe.
Since I fixed the charset between PHP and MySQL, new INSERTs are now storing correctly. However, I want to fix all the older rows that are "messed" at the moment. I tried many things already, but it always breaks the strings on the first "illegal" character. Here is my current code:
$m = mysql_real_escape_string('¿<?php echo "¬<b>\'PHP á (á)ţăriîş </b>"; ?> ă-ţi abcdd;//;ñç´พดแทฝใจคçăâξβψδπλξξςαยนñ ;');
mysql_set_charset('utf8');
mysql_query('INSERT INTO `table` SET `name`="'.$m.'"');
mysql_set_charset('latin1');
mysql_query('INSERT INTO `table` SET `name`="'.$m.'"');
mysql_set_charset('utf8');
$result = mysql_iquery('SELECT * FROM `table`');
while ($row = mysql_fetch_assoc($result)) {
$message = $row['name'];
$message = mb_convert_encoding($message, 'ISO-8859-15', 'UTF-8');
//$message = iconv("UTF-8", "ISO-8859-1//IGNORE", $message);
mysql_iquery('UPDATE `table` SET `name`="'.mysql_real_escape_string($message).'" WHERE `a1`="'.$row['a1'].'"');
}
It "UPDATE"s with the expected characters, except that the string gets truncated after the character "ă". I mean, that character and following chars are not included on the string.
Also, testing with the "iconv()" (that is commented on the code) does the same, even with //IGNORE and //TRANSLIT
I also tested several charsets, between ISO-8859-1 and ISO-8859-15.
From what you describe, it seems you have UTF-8 data that was originally stored as Latin-1 and then not converted correctly to UTF-8. The data is recoverable; you'll need a MySQL function like
convert(cast(convert(name using latin1) as binary) using utf8)
It's possible that you may need to omit the inner conversion, depending on how the data was altered during the encoding conversion.
After I searched about an hour or two for this answer, I needed to migrate an old tt_news db from typo into a new typo3 version. I tried to convert the charset in the export file and import it back already, but didn't get it working.
Then I tried the answer above from ABS and started an update on the table:
UPDATE tt_news SET
title=convert(cast(convert(title using latin1) as binary) using utf8),
short=convert(cast(convert(short using latin1) as binary) using utf8),
bodytext=convert(cast(convert(bodytext using latin1) as binary) using utf8)
WHERE 1
You can also convert imagecaption, imagealttext, imagetitletext and keywords if needed.
Hope this will help somebody migrating tt_news to new typo3 version.
the way is better way
use connection tow you database normal
then use this code to make what you need
you must make your page encoding utf-8 by meta in header cod html (dont forget this)
then use this code
$result = mysql_query('SELECT * FROM shops');
while ($row = mysql_fetch_assoc($
$name= iconv("windows-1256", "UTF-8", $row['name']);
mysql_query("SET NAMES 'utf8'");
mysql_query("update `shops` SET `name`='".$name."' where ID='$row[ID]' ");
}
I highly recommend using 'utf8mb4' instead of 'utf8', since utf8 cannot store some chinese characters and emojis.