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:
在阅读了这里和其他地方的许多技巧之后,我想我终于完成了GET查询,PHP和MYSQL都使用utf8。但是,在匹配的字符串包含非ascii字符的情况下,无法使用简单的查询。我的(简化的)代码是:
$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.
如果“first”是ascii,那么查询就可以工作,如果它包含重音字符,那么它就不能工作。当我打印出db(在php生成的表中)时,它看起来很好,就像在phpadmin中查看一样。
What am I doing wrong? Do I need to tell the '=' operator to use utf8? Why?
我做错了什么?我需要告诉'='操作符使用utf8吗?为什么?
Thanks
谢谢
abo
土著居民的
2 个解决方案
#1
2
What's the character set of the table itself ?
表本身的字符集是什么?
Also, try running the following query just after connection:
另外,尝试在连接之后运行以下查询:
SET NAMES UTF8;
#2
1
Have you tried encoding the name as UTF-8 before the query?
您试过在查询之前将名称编码为UTF-8吗?
$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.
如果这还不行,试试utf8_decode。这听起来很奇怪,但我有一些很奇怪的例子。
#1
2
What's the character set of the table itself ?
表本身的字符集是什么?
Also, try running the following query just after connection:
另外,尝试在连接之后运行以下查询:
SET NAMES UTF8;
#2
1
Have you tried encoding the name as UTF-8 before the query?
您试过在查询之前将名称编码为UTF-8吗?
$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.
如果这还不行,试试utf8_decode。这听起来很奇怪,但我有一些很奇怪的例子。