1

我正在尝试通过 php 将非英语字符(例如:Josef Kricenský)插入我的 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 插入它可以工作,所以我的猜测是代码缺少一些东西,顺便说一句 php 版本是 5.2.7

4

2 回答 2

0

似乎在我的机器上运行良好的独立示例......

<?php
// added numeric code entity to reflect actual code of OP
// $param = 'Josef Kricenský';
$param = 'Josef Kricensk&#253;';
$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
于 2012-12-05T11:45:49.270 回答
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)" );
于 2012-12-05T11:56:01.477 回答