无法使用PHP将记录插入到mysql数据中

时间:2012-08-09 17:40:15

标签: php mysql

我正在使用PHP来填充公司记录的数据库。我有一个公司名称字段和他们使用的货币类型 但是当我使用PHP时,如果货币是Enlglish英镑符号(£),那么记录永远不会被插入。美元符号($)或任何其他正常字符都没问题。当我运行sql语句并将其直接输入MySQL Query Browser时,带有井号的记录就可以正常插入。但是当我在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 Query Browser中,“Table Options”选项卡显示对于这个company_test表,我的字符集是utf8。

感谢。

3 个答案:

答案 0 :(得分:1)

检查错误:

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

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

答案 1 :(得分:1)

经过一些谷歌搜索,我终于发现了一些有用的东西。有类似的人可能创建了一个PHP函数来转换sql语句的字符集 现在我的查询在插入之前看起来像这样: INSERT INTO company_test(名称,货币)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; 
    } 

}

答案 2 :(得分:-1)

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

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

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