简体   繁体   English

PHP / MySQL中的PDO和UTF-8特殊字符?

[英]PDO and UTF-8 special characters in PHP / MySQL?

I am using MySQL and PHP 5.3 and tried this code. 我正在使用MySQL和PHP 5.3,并尝试了此代码。

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$con = mysql_connect("localhost", "root", "");
mysql_set_charset('utf8');
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("kdict", $con);
$sql = "SELECT * FROM `en-kh` where english='a'";
echo $sql;
$result = mysql_query($sql);

while($row = mysql_fetch_array($result))
{
  echo $row['english'] . " </br> " . $row['khmer'];
  echo "<br />";
}
?>

=> I got good UTF-8 render display, well done. =>我有很好的UTF-8渲染显示,做得很好。

But for now I create a class PDO to keep easy to extend and more easy 但是现在,我创建了一个类PDO,以使其易于扩展并且更加容易

 class crud {
     // code..
     public function conn()
     {
         isset($this->username);
         isset($this->password);
         if (!$this->db instanceof PDO)
         {
             $this->db = new PDO($this->dsn, $this->username, $this->password);
             $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
             $this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");   
          }
      }
      /*more code here*/
}



/*** a new crud object ***/
$crud = new crud();
/*** The DSN ***/
$crud->dsn = "mysql:dbname=kdict;host=localhost";

/*** MySQL username and password ***/
$crud->username = 'root';
$crud->password = '';
/*** select all records from table ***/
$records = $crud->rawSelect("SELECT * FROM `en-kh` where english='a'");

/*** fetch only associative array of values ***/
$rows = $records->fetchAll(PDO::FETCH_ASSOC);

/*** display the records ***/
foreach($rows as $row)
{
    foreach($row as $fieldname=>$value)
    {
        echo $fieldname.' = '.$value.'<br />';
    }
    echo '<hr />';
}
?>

But it displays my character something like this '????' 但是它显示了我的性格,例如“ ????”

I found this link on Stack Overflow, it looks like the same problem i met Special characters in PHP / MySQL 我在Stack Overflow上找到了此链接,看起来就像是我在PHP / MySQL中遇到特殊字符的问题

It looks the same as my problem => I tried to fix it, but I still doesn't work. 它看起来与我的问题相同=>我试图修复它,但仍然无法正常工作。

$this->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAME'utf8'");

Can anyone tell me what the problem is? 谁能告诉我问题出在哪里? How can I correct it? 我该如何纠正?

thanks 谢谢

You're missing an S : it's SET NAMES and not SET NAME : 您缺少S它是SET NAMES而不是SET NAME

$this->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");

You also need to un-comment it of course. 当然,您还需要取消注释。 Also, PDO::MYSQL_ATTR_INIT_COMMAND can not be set with PDO::setAttribute() after you've established your database connection (the constant name says it all), you've to specify it in the constructor using the $driver_options argument, like this: 同样,在建立数据库连接(常量名称说明了一切)之后, 无法使用PDO::setAttribute() 设置 PDO::MYSQL_ATTR_INIT_COMMAND ,您必须使用$driver_options参数在构造函数中指定它,例如这个:

$this->db = new PDO($this->dsn, $this->username, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

An alternative to this is to just execute that very same query immediately after connecting: 替代方法是在连接后立即执行相同的查询:

$this->db = new PDO($this->dsn, $this->username, $this->password);
$this->db->exec("SET NAMES 'utf8';");

I had the same trouble and found out after trying out 1000000 different options that the default mysql engine still remains MyISAM. 我遇到了同样的麻烦,在尝试了1000000个不同的选项后发现默认的mysql引擎仍然是MyISAM。

Verifying that InnoDB is the Default Storage Engine as such: 验证InnoDB是否是默认存储引擎,如下所示:

Issue the command SHOW VARIABLES LIKE 'have_innodb'; 发出命令SHOW VARIABLES LIKE 'have_innodb'; to confirm that InnoDB is available at all. 确认InnoDB完全可用。

Then issue the command SHOW ENGINES; 然后发出命令SHOW ENGINES; to see all the different MySQL storage engines. 查看所有不同的MySQL存储引擎。

Look for DEFAULT in the InnoDB line and NOT in the MyISAM line. InnoDB行而不是MyISAM行中查找DEFAULT I realized that my provided had a setting preventing me from changing the default engine using SET storage_engine=MYISAM; 我意识到我提供的设置阻止我使用SET storage_engine=MYISAM;更改默认引擎SET storage_engine=MYISAM; . In my case, I contacted my provider and was directed to where I could change the option to be able to change the default engine. 就我而言,我联系了我的提供商,并被引导到可以更改选项的位置,以便能够更改默认引擎。 Hope this helps! 希望这可以帮助!

The possible way to insert Special characters using PDO, just follow the these to steps: 使用PDO插入特殊字符的可能方法,只需按照以下步骤操作:

1) Set the Attribute to you connection class. 1)将属性设置为您的连接类。

$this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAME'utf8'");

2) Now you can use htmlspecialchars while query creation and insertion to database: 2)现在,您可以在创建查询并将其插入数据库时​​使用htmlspecialchars:

$ShortDescription   = htmlspecialchars($_POST['ShortDescription'], ENT_QUOTES);
$LongDescription    = htmlspecialchars($_POST['LongDescription'],ENT_QUOTES);

And it will work fine. 它将正常工作。

I suggest always connecting to a database via PDO. 我建议始终通过PDO连接到数据库。

Below is a sample code; 下面是示例代码;

<?php

class connMysql {

    protected static $instance;
    private static $database_type = "mysql";    
    private static $hostname = "localhost";
    private static $user = “database_user”;
    private static $password = “database_user_password”;
    private static $database_name = “your_database”;

    private static $persistent = false;

    private function __construct() {

        try {
            self::$instance = new \PDO(self::$database_type . ":host=" . self::$hostname . ";dbname=" . self::$database_name
                    , self::$user
                    , self::$password
                    , array(
                \PDO::ATTR_PERSISTENT => self::$persistent,
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
                \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
                \PDO::ATTR_STRINGIFY_FETCHES => true,
                \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
            ));
        } catch (PDOException $e) {
            echo "Connection Error: " . $e->getMessage();
        }
    }

    public static function getInstance() {
        if (!self::$instance) {
            new connMysql();
        }

        return self::$instance;
    }

    public static function close() {
        self::$instance = null;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM