2

我正在使用 PHP 来填充公司记录的数据库。我有一个公司名称和他们使用的货币类型的字段。
但是当我使用 PHP 时,如果货币是英语英镑符号 (£),则永远不会插入记录。美元符号 ($) 或任何其他正常字符都没有问题。当我运行 sql 语句并将其直接输入 MySQL 查询浏览器时,带有井号的记录插入得很好。但是当我在 PHP 中运行完全相同的 INSERT 语句时,它就不起作用了。

$sql = "INSERT INTO company_test (name, currency) VALUES ('ABC Widgets', '£')";   
$rs = mysql_query($sql, $conn);
//Does not insert a record

$sql = "INSERT INTO company_test (name, currency) VALUES ('ABC Widgets', '$')";   
$rs = mysql_query($sql, $conn);
//A record inserts just fine

//My MySQL version is 5.5.11.  PHP is version 5.3.6.  
//The MySQL table looks like this:
TABLE company_test
FIELD | id       | INTEGER(10) | not null | auto increment
FIELD | name     | VARCHAR(45) | not null
FIELD | currency | VARCHAR(3)  

在 MySQL 查询浏览器中,“表选项”选项卡显示,对于这个 company_test 表,我的字符集是 utf8。

谢谢。

4

3 回答 3

1

检查错误:

$rs = mysql_query($sql, $conn) or die(mysql_error());
                               ^^^^^^^^^^^^^^^^^^^^^

永远不要假设查询成功。即使您的 sql 语法是完美的,也有太多其他原因导致无法检查。

于 2012-08-09T17:47:05.887 回答
1

经过一番谷歌搜索,我终于找到了一些有用的东西。类似的人可能创建了一个转换 sql 语句字符集的 PHP 函数。
现在我的查询在插入之前看起来像这样: INSERT INTO company_test (name, currency) VALUES ('ABC Widgets', '£') 注意井号之前的有趣小字符。

无论如何,这里是功能:

function TtoUtf8( &$string, $encType = 'ISO-8859-1' ) 
{ 
    $enc    = mb_detect_encoding( $string ); 
    $enc ? 
        $enc = $enc : 
        $enc = $encType; 
    if ( $enc == 'UTF-8' ) 
    { 
        return $string; 

        // end if $enc == UTF-8 
    } else 
    { 
        $conv = iconv( $enc, 'UTF-8//TRANSLIT', $string ); 
        $conv ? 
            $ret = &$conv : 
            $ret = &$string; 
        return $ret; 
    } 

}

于 2012-08-09T20:28:16.333 回答
-1

为什么不先将其转换为 htmlentities 或 htmlspecialchar:

$currency = htmlspecialchars('£');
$sql = "INSERT INTO company_test (name, currency) VALUES ('ABC Widgets', '{$currency}')"; 

另外,您的货币字段是什么类型的数据类型?

于 2012-08-09T17:49:01.437 回答