Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO: charset, set names?

Tags:

php

mysql

pdo

I had this previously in my normal mysql_* connection:

mysql_set_charset("utf8",$link); mysql_query("SET NAMES 'UTF8'"); 

Do I need it for the PDO? And where should I have it?

$connect = new PDO("mysql:host=$host;dbname=$db", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); 
like image 639
Karem Avatar asked Dec 05 '10 21:12

Karem


People also ask

How to set charset in PDO?

In PDO the charset can be specified in the connection string: $conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass); The charset option is only used since PHP 5.3. 6, so take this into account when running an older version of PHP.

What is PDO in php MySQL?

PHP PDO is a database access layer that provides a uniform interface for working with multiple databases. PDO simplifies the common database operations including: Creating database connections. Executing queries using prepared statements. Calling stored procedures.


2 Answers

You'll have it in your connection string like:

"mysql:host=$host;dbname=$db;charset=utf8mb4" 

HOWEVER, prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:

$dbh = new PDO("mysql:host=$host;dbname=$db",  $user, $password); $dbh->exec("set names utf8mb4"); 
like image 148
Cobra_Fast Avatar answered Sep 21 '22 14:09

Cobra_Fast


Prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:

<?php      $dbh = new PDO("mysql:$connstr",  $user, $password);      $dbh -> exec("set names utf8");  ?> 
like image 21
9nix00 Avatar answered Sep 22 '22 14:09

9nix00