【问题标题】:Is mysqli bind_param the culprit? Cannot save special characters like €mysqli bind_param 是罪魁祸首吗?无法保存特殊字符,例如 €
【发布时间】:2011-11-19 20:53:17
【问题描述】:

我正在尝试使用 PHP / MySQL 创建一些页面。

我的数据库表设置为utf8_general_ci,表列​​也是如此。如果我使用 phpmyadmin 并手动插入一个页面,我可以输入我想要的所有€,它们将作为€插入。我也可以完美展现。

但是,当我尝试使用 mysqli 插入页面时,€ 将转换为 €

我没有进行任何形式的转换。如果我在即将插入页面之前回显页面列字段,它仍然会正确显示€。

代码:

$connection = new mysqli('localhost', 'root', '', 'some_db');

$query  = 'INSERT INTO page (ID, title, content) VALUES (?, ?, ?)';
$params = array('iss', 'NULL', 'test title', '€ some content');

$stmt = $connection->prepare($query);

call_user_func_array(array($stmt, 'bind_param'), by_ref($params));

$stmt->execute();

by_ref 函数只做一个引用,没有别的。一切正常,除了它没有正确插入€时让我头疼。也许它不是 bind_param,而是别的东西。不过我想知道答案!

更新:

感谢 Digital Precision,我发现我必须确保连接将使用“utf8”。但是,我只需要在使用 INSERT 或 UPDATE 时设置它,因为 SELECT 确实在 utf8 中返回了结果。希望这可以帮助某人

【问题讨论】:

    标签: php mysqli


    【解决方案1】:

    PHPMyAdmin 可能将连接字符集显式设置为 UTF-8,这就是为什么它可以通过管理界面而不是通过您的脚本工作的原因。查看mysqli::set_charset 了解更多详细信息。

    $connection->set_charset('utf8');
    

    编辑

    尝试取出 call_user_function:

    $connection = new mysqli('localhost', 'root', '', 'some_db');
    
    $query  = 'INSERT INTO page (ID, title, content) VALUES (?, ?, ?)';
    //$params = array('iss', 'NULL', 'test title', '€ some content');
    
    $stmt = $connection->prepare($query);
    
    // Replace this
    //call_user_func_array(array($stmt, 'bind_param'), by_ref($params));
    
    // With this
    $stmt->bind_param('iss', 'NULL', 'test title', '€ some content'); 
    
    $stmt->execute();
    

    【讨论】:

    • 插入时对我没有帮助,但会使选择页面更加奇怪(即 € 再次转换为 €)
    • @Tessmore:试试$connection->get_charset(),看看当前值是多少。
    • @Tessmore:还有一些其他的尝试;在不使用绑定的情况下尝试查询,并尝试在 call_user_func_array 之外进行绑定。
    • 没有get_charset();,但如果你提到character_set_name();,它会在不设置字符集的情况下返回latin1,但我按照你的建议做了set_charset('utf8');,它给了我utf8编码,但仍然是€ 正在转换中。我现在将尝试使用不带绑定的查询,但我不知道您在 call_user_func_array 之外设置绑定是什么意思。
    • 没有 bind_param 它可以工作......但我需要使用 bind_params 来避免 SQL 注入
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    相关资源
    最近更新 更多