无法使用适当的字符集更新列

时间:2015-03-20 22:21:23

标签: php mysql non-ascii-characters

我遇到了编码的一个大问题,更准确地说是我的数据库中的条目。插入数据时,字符显示正确。但是,当我尝试更新列时,字符被误读为其中一个:авдвадва。同时,当我插入新行时,phpMyAdmin中的数据如下所示:Кон

<form action="addItem.php" method="post">
    <p>
        <label class='title' for="title"> Title</label>
        <input type="text" name="title" id="title" class="input"/>
    </p>

    <p>
        <label class='description' for="description"> Description</label>
        <textarea name="description" id="description" rows="10" cols="35"></textarea>
    </p>    

    <p>
        <input type="submit" class='buttono' name="addEntry" id="addEntry" value="Add New Entry" />
    </p>
</form>

这是我的 db.php

<?php

class Db {

    public $mysql;

    function __construct() {
        $this->mysql = new mysqli('localhost', 'root', 'password', 'to-do') or die("Unable to connect to database");
    }

    function delete_by_id($id) {
        $query = "DELETE from todo WHERE id = $id";
        $result = $this->mysql->query($query) or die("There was a problem");
    }

    function update_by_id($id, $description) {
        $query = "UPDATE todo
                 SET description = ?
                 WHERE id = ?";

         if ($stmt = $this->mysql->prepare($query)) {
            $stmt->bind_param('si', $description, $id);
            $stmt->execute();
         }
    }

}

这是我的 addItem.php

<?php

require 'db.php';
$db = new Db();

if (isset($_POST['addEntry'])) {
    $query = "INSERT INTO todo VALUES ('', ?, ?)";

    if ($stmt = $db->mysql->prepare($query)) {
        $stmt->bind_param('ss', $_POST['title'], $_POST['description']);
        $stmt->execute();
        header('Location: index.php');
    }

} else {
    die ($db->mysql->error);
}

它出了什么问题?在查询执行之前我尝试将字符集设置为UTF-8,但它仍然是相同的(实际上这似乎不是问题)。

1 个答案:

答案 0 :(得分:0)

您必须将mysql连接字符集设置为UTF-8。您可以像这样使用$ mysql-&gt; set_charset(“utf8”):

<?php

class Db {

    public $mysql;

    function __construct() {
      $this->mysql = new mysqli('localhost', 'root', 'password', 'to-do') or die("Unable to connect to database");
      if (!$this->mysql->set_charset("utf8")) {
        throw new Exception("Error loading character set utf8: " .  $this->mysql->error);
      }

    }

    function delete_by_id($id) {
        $query = "DELETE from todo WHERE id = $id";
        $result = $this->mysql->query($query) or die("There was a problem");
    }

    function update_by_id($id, $description) {
        $query = "UPDATE todo
                 SET description = ?
                 WHERE id = ?";

         if ($stmt = $this->mysql->prepare($query)) {
            $stmt->bind_param('si', $description, $id);
            $stmt->execute();
         }
    }

}