今天在写一个PHP脚本访问数据库时,发现其中的中文字符串使用了HTML编码方式进行存储的(比如中文字“毛”对应的HTML编码为“毛”),使得在对该字段进行条件查询时不能进接使用中文进行查询,而要将其转换为编码后再进行条件匹配。
PHP中对可读性字符与HTML编码字符相互转换时需要使用到htmlentities和html_entity_decode函数。于是写出如下查询语句,
代码
$sql
=
"
select id,depart_name,first_name,last_name,local_name,extension,mobile,title
"
;
$sql .= " from pb_extension e, pb_department d " ;
$sql .= " where e.depart_id = d.depart_id " ;
$sql .= " and d.plant=' " . $plant . " ' " ;
$sql .= " and (first_name like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " or last_name like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " or local_name like '% " . htmlentities ( $HTTP_POST_VARS [ " q " ]) . " %' " ;
$sql .= " or extension like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " or mobile like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " or depart_name like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " or title like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " ) " ;
$sql .= " from pb_extension e, pb_department d " ;
$sql .= " where e.depart_id = d.depart_id " ;
$sql .= " and d.plant=' " . $plant . " ' " ;
$sql .= " and (first_name like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " or last_name like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " or local_name like '% " . htmlentities ( $HTTP_POST_VARS [ " q " ]) . " %' " ;
$sql .= " or extension like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " or mobile like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " or depart_name like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " or title like '% " . $HTTP_POST_VARS [ " q " ] . " %' " ;
$sql .= " ) " ;
并执行。可是怪是却发生了,此语句在SQL Analyzer中可以正确执行并查询出结果,而在IE中很执行这段脚本却提示查询结果为零,这是为什么呢?
经过仔细检查这段SQL,并查看在IE中的源码,发现了问题的根结所在。查询值经htmlentities函数后转换为HTML编码,此编码中存在着特殊字符&(如第一段中的举例),在IE中这个字符是另有含义的。在IE中一般都是使用“&”来表示这个符号的,导致在IE中看到输出的SQL语句和真正执行的语句是不一样的。
要解决这个问题就要想个办法不让IE使用“&”表示“&”符号。经过一翻查询,发现使用如下代码可以解决这个问题。
代码
<?
php
$trans = get_html_translation_table (HTML_ENTITIES);
$trans = array_flip ( $trans );
$encoded = " Hallo & <Frau> & Krämer " ;
$original = strtr ( $encoded , $trans );
echo $original ;
?>
$trans = get_html_translation_table (HTML_ENTITIES);
$trans = array_flip ( $trans );
$encoded = " Hallo & <Frau> & Krämer " ;
$original = strtr ( $encoded , $trans );
echo $original ;
?>
执行这段代码,输出的$original变量值为“Hallo & <Frau> & Krämer”,这正是我想要的结果。
以上是我在工作中遇到的问题及解决方法,特将其写在我的Blog上,与那些遇到和我相似问题的朋友们一起分享。