gpt4 book ai didi

php - 无法将外语字符插入数据库

转载 作者:行者123 更新时间:2023-11-30 23:25:09 26 4
gpt4 key购买 nike

我正在尝试通过 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

最佳答案

似乎在我的机器上运行良好的自包含示例...

<?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

关于php - 无法将外语字符插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13722170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com