Guest User

Untitled

a guest
Aug 16th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. PDO and UTF-8 Special characters in PHP / MySQL?
  2. $dbhost = 'localhost';
  3. $dbuser = 'root';
  4. $dbpass = '';
  5. $con = mysql_connect("localhost","root","");
  6. mysql_set_charset('utf8');
  7. if (!$con)
  8. {
  9. die('Could not connect: ' . mysql_error());
  10. }
  11.  
  12. mysql_select_db("kdict", $con);
  13. $sql = "SELECT * FROM `en-kh` where english='a'";
  14. echo $sql;
  15. $result = mysql_query($sql);
  16.  
  17. while($row = mysql_fetch_array($result))
  18. {
  19. echo $row['english'] . " </br> " . $row['khmer'];
  20. echo "<br />";
  21. }
  22. ?>
  23.  
  24. class crud {
  25. //code..
  26. public function conn()
  27. {
  28. isset($this->username);
  29. isset($this->password);
  30. if (!$this->db instanceof PDO)
  31. {
  32. $this->db = new PDO($this->dsn, $this->username, $this->password);
  33. $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  34. $this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
  35.  
  36. }
  37. }
  38. /*more code here*/
  39. }
  40.  
  41.  
  42.  
  43. /*** a new crud object ***/
  44. $crud = new crud();
  45. /*** The DSN ***/
  46. $crud->dsn = "mysql:dbname=kdict;host=localhost";
  47.  
  48. /*** MySQL username and password ***/
  49. $crud->username = 'root';
  50. $crud->password = '';
  51. /*** select all records from table ***/
  52. $records = $crud->rawSelect("SELECT * FROM `en-kh` where english='a'");
  53.  
  54. /*** fetch only associative array of values ***/
  55. $rows = $records->fetchAll(PDO::FETCH_ASSOC);
  56.  
  57. /*** display the records ***/
  58. foreach($rows as $row)
  59. {
  60. foreach($row as $fieldname=>$value)
  61. {
  62. echo $fieldname.' = '.$value.'<br />';
  63. }
  64. echo '<hr />';
  65. }
  66. ?>
  67.  
  68. $this->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
  69.  
  70. $this->db = new PDO($this->dsn, $this->username, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
  71.  
  72. $this->db = new PDO($this->dsn, $this->username, $this->password);
  73. $this->db->exec("SET NAMES 'utf8';");
Add Comment
Please, Sign In to add comment