我正在使用PHP和MySQL innodb(PDO),下面是表格的结构。
CREATE TABLE `articles` (
`id` int(11) NOT NULL,
`feed_id` mediumint(8) unsigned NOT NULL,
`title` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
`pubdate` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`loaddate` date DEFAULT NULL,
`uniqid` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`source` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`,`feed_id`),
KEY `feed_id` (`feed_id`),
KEY `link` (`link`,`uniqid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
这是我的PHP代码
$DB->sql = "INSERT INTO feed_articles (feed_id,title,link,description,image,video,audio,pubdate,loaddate,uniqid,source) VALUES ";
$DB->sql .= "(".$pfid.",".$DB->quote($RSSarticles[$i]["title"])
.",".$DB->quote($RSSarticles[$i]["link"])
.",".$DB->quote($RSSarticles[$i]["desc"])
.",".(isset($RSSarticles[$i]["image"])?$DB->quote($RSSarticles[$i]["image"]):"''")
.",".(isset($RSSarticles[$i]["video"])?$DB->quote($RSSarticles[$i]["video"]):"''")
.",".(isset($RSSarticles[$i]["audio"])?$DB->quote($RSSarticles[$i]["audio"]):"''")
.",".$DB->quote($RSSarticles[$i]["date"])
.",CURRENT_DATE,"
.$DB->quote($RSSarticles[$i]["id"])
.",".$DB->quote($RSSarticles[$i]["source"])
.") ";
$DB->execute($DB->sql);
问题是它没有正确写入其他语言字符,它正在进行一些转换并写入数据库。如果我直接复制粘贴到数据库中,那就没问题了。但是使用 PHP,我不确定出了什么问题。
任何人都知道我应该如何让它适用于所有语言,如中文/德语/俄语
我正在做的每个连接的更新。
function connection($server,$usernamedb,$passworddb,$dbname)
{
//$this->id = @mysql_connect($server, $usernamedb, $passworddb);
$this->id = mysql_connect($server, $usernamedb, $passworddb);
if ($this->id)
{
$this->selectDB($dbname);
$this->setUtf8();
}
else
{
$this->warning();
}
}
function setUtf8()
{
$this->execute("SET NAMES 'utf8' ");
$this->execute("SET CHARACTER SET 'utf8' ");
}
但是我在PHP配置中观察到一件事default_charset= ISO-8859-1是导致问题吗??
数据库是UTF8格式,所以没有问题。
谢谢。蒙纳
您必须使用 mysqli::set_charset 将连接字符集设置为 utf8。请检查$RSSarticles
数组的内容是否确实是utf8 - 如果不是,您必须先自己转换它。
Kindly set your database default character set to utf8
using following command
ALTER DATABASE db_name
DEFAULT CHARACTER SET utf8
and also set character set in php file using following code in first line of php
<?php
header('Content-Type: text/html; charset=utf-8');
?>
编辑以匹配更新:
是的,您应该将配置设置default_charset
设置为 UTF-8。始终尝试在应用程序的所有部分(网站代码、客户端代码、数据库)中仅使用一个字符集
原答案如下:
您已经发现了处理UTF-8,PHP和数据库时的一个模糊障碍。
我假设您的输入数据是 UTF-8?
即使您的 PHP 脚本、数据库表和字段采用 UTF-8,您仍然需要告诉您的数据库适配器在传输和连接上使用 UTF-8。
实现此目的的最简单方法是在建立数据库连接后使用 SET NAMES
语句。
$DB->execute("SET NAMES 'utf8'");
应该足够了