我正试图通过php将非英文字符(例如:JosefKricenský)插入我的mysql数据库
这是我的代码
$name=addslashes("Josef Kricenský");
$id=1;
mysql_query("'SET NAMES 'utf8'");
mysql_query("insert ignore into names (id,value) values ('$id','$name')");
数据正在插入表中,但它只插入'ý',即:Josef Kricensk
utf8_general_ci是表格排序,MyISAM是存储引擎,此代码以前在我的其他网站上有效,但似乎缺少此内容。
如果我通过phpMyadmin插入它可行,所以我的猜测是代码缺少了什么,BTW php版本是5.2.7
答案 0 :(得分:0)
自包含的示例似乎在我的机器上正常工作......
<?php
// added numeric code entity to reflect actual code of OP
// $param = 'Josef Kricenský';
$param = 'Josef Kricenský';
$param = html_entity_decode($param , ENT_XML1, 'UTF-8');
// this is not how you check for utf-8 encoding
// ...except in this simple example ;-)
// all characters but the ý are encoded in one byte, ý uses two bytes
// -> 16 bytes -> strlen($param) should be 16
if ( 16!=strlen($param) ) {
die("this doesn't seem to be utf-8 encoded");
}
// the mysql_ api is deprecated. Take a look at e.g. http://docs.php.net/pdo for alternatives
$mysql = mysql_connect('localhost', 'localonly', 'localonly') or die(mysql_error());
mysql_select_db('test', $mysql) or die(mysql_error($mysql));
// SET NAMES 'utf8' doesn't tell the client library about the changed encoded
// so e.g. mysql_real_escape_string() may fail
// see http://docs.php.net/mysql_set_charset
mysql_set_charset('utf8', $mysql) or die(mysql_error($mysql));
// using a temporary table for this example...
setup($mysql);
// insert a record
echo "insert a record\n";
$query = sprintf("INSERT INTO soFoo (name) VALUES ('%s')",
mysql_real_escape_string($param, $mysql)
);
mysql_query($query, $mysql) or die(mysql_error($mysql));
// retrieve the record
echo "retrieve the record\n";
$result = mysql_query('SELECT name FROM soFoo', $mysql) or die(mysql_error($mysql));
while( false!==($row=mysql_fetch_assoc($result)) ) {
echo 'strlen($row[name])==', strlen($row['name']), "\n";
}
function setup($mysql) {
mysql_query('
CREATE TEMPORARY TABLE soFoo(
id int auto_increment,
name varchar(32),
primary key(id)
) DEFAULT CHARSET=utf8
', $mysql) or die(mysql_error($mysql));
}
打印
insert a record
retrieve the record
strlen($row[name])==16
答案 1 :(得分:0)
尝试运行此功能。
<?php
$name = "Josef Kricenský";
$id = 1;
if( substr( $name, 14, 2 ) !== "\xC3\xBD" ) {
trigger_error( "This file was not saved in UTF-8. Set your text editor to save the file in UTF-8" );
}
//Connect to mysql
mysql_set_charset( "utf8" );
$name_safe = "'" . mysql_real_escape_string( $name ) . "'";
$id_safe = (int)$id;
mysql_query( "insert ignore into names (id,value) values ($id_safe, $name_safe)" );