简体   繁体   中英

Problem in query (PHP MYSQL UTF-8 )

After reading the many tips here and elsewhere, I think I have finally made my GET query, PHP and MYSQL all talk utf8. However, I cannot get a simple query to work where the string I'm matching contains non-ascii characters. My (simplified) code is:

$link = mysql_connect("h", "u", "p") or die(mysql_error());
mysql_select_db("db", $link) or die(mysql_error($link));
mysql_set_charset("utf8", $link); //connection charset
$name = mysql_real_escape_string($_GET['first'], $link);
$query = sprintf("SELECT name, date FROM guestbook WHERE name='%s'", $name);
$result = mysql_query($query, $link) or die(mysql_error()); 
if (mysql_num_rows($result) == 0) {
...
}

If 'first' is ascii, then the query works, if it contains accented characters it does not. When I print out the db (in an table generated by php) it looks just fine, as does viewing in it phpadmin.

What am I doing wrong? Do I need to tell the '=' operator to use utf8? Why?

Thanks

abo

What's the character set of the table itself ?

Also, try running the following query just after connection:

SET NAMES UTF8;

Have you tried encoding the name as UTF-8 before the query?

$query = sprintf("SELECT name, date FROM guestbook WHERE name='%s'", utf8_encode($name));

If that doesn't do the trick, try utf8_decode . It sounds weird but I had weird cases where it did the trick.

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