我正在尝试使用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中给了我结果。希望这有助于某人
答案 0 :(得分:3)
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();