我的数据库中有一个名为127.0.0.1
的表格,编码在pages
中(包含utf8_unicode_ci
,id
,title
和template
列)。
当我使用phpMyAdmin将希伯来文本插入数据库时,它运行正常,我看到了希伯来语文本。但是当我从php文件中插入行时,它会向数据库插入乱码(content
而不是בלה
和מכבי
而不是גכדדגכ
。
这些是我的文件:
的index.php
תל אביב
class.database.php
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<?php
include "includes/class.database.php";
include "includes/class.page.php";
$db = Database::getInstance("localhost", "dsite", "root", "");
$page = new Page();
$page->setTitle("מכבי");
$page->setTemplate("one");
$page->setContent("תל אביב");
$page->save();
$page->setTitle("בלה");
$page->setContent("גכדדגכ");
$page->save();
?>
</body>
class.page.php
<?php
class Database
{
private $connection;
private static $instance = null;
private function __construct($host = "", $name = "", $username = "", $password = "")
{
$this->connection = new mysqli($host, $username, $password, $name);
if ($this->connection->connect_errno > 0)
die ($this->connection->connect_error);
}
public static function getInstance($host = "", $name = "", $username = "", $password = "")
{
if (!self::$instance)
self::$instance = new Database($host, $name, $username, $password);
return self::$instance;
}
public function getConnection()
{
return $this->connection;
}
public function getLastId()
{
return $this->connection->insert_id;
}
public function query($q)
{
return $this->connection->query($q);
}
}
使用Notepad ++创建的所有文件,编码设置为<?php
class Page
{
private $id;
private $title;
private $template;
private $content;
private $db;
public function __construct($pageID = 0)
{
$this->db = Database::getInstance();
if ($pageID > 0)
{
$selectPage = $this->db->query("SELECT * FROM `pages` WHERE `id`='$pageID'");
if ($selectPage->num_rows > 0)
{
$page = $selectPage->fetch_assoc();
$this->id = $page['id'];
$this->title = $page['title'];
$this->template = $page['template'];
$this->content = $page['content'];
}
}
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
public function setTemplate($template)
{
$this->template = $template;
}
public function getTemplate()
{
return $this->template;
}
public function setContent($content)
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function save()
{
if ($this->id == 0)
{
$this->db->query("INSERT INTO `pages` (`title`,`template`,`content`) VALUES ('{$this->title}','{$this->template}','{$this->content}')");
$this->id = $this->db->getLastId();
}
else
{
$this->db->query("UPDATE `pages` SET `title`='{$this->title}', `template`='{$this->template}', `content`='{$this->content}' WHERE `id`='{$this->id}'");
}
}
}
。
答案 0 :(得分:1)
尝试在 class.database.php 的__construct()
中设置字符集,如下所示:
$this->connection->set_charset("utf8")