Chama
Chama

Reputation: 199

PDO: Multiple commands in PDO::MYSQL_ATTR_INIT_COMMAND

i'm using this PDO connection:

try{

$db=new PDO("
mysql:host=localhost;
dbname=...",
"dbu...",
"pass",
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET lc_time_names='de_DE'"));
}
catch(PDOException $e){die("Error!");}

Now i would like to add another init command:

array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET lc_time_names='de_DE'",
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
)

But it looks like that the utf8-one overwrites the first init command.

So i've tried this one but also without success:

array(
PDO::MYSQL_ATTR_INIT_COMMAND => array("SET lc_time_names='de_DE'","SET NAMES utf8")
)

Any idea how to send more than just one init command?

Thanks!

Upvotes: 7

Views: 9839

Answers (2)

fusion3k
fusion3k

Reputation: 11689

PDO doesn't support multiple PDO::MYSQL_ATTR_INIT_COMMAND options. However, in case you need to execute multiple SET commands, you can use a workaround:

array
(
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET lc_time_names='de_DE',NAMES utf8"
)

From MySQL documentation:

A SET statement can contain multiple variable assignments, separated by commas.

Note that regarding the SET NAMES command, it is the recommended to use the charset DSN option instead.

Upvotes: 36

Your Common Sense
Your Common Sense

Reputation: 157919

  1. You don't need it. Everything you're trying to put in PDO::MYSQL_ATTR_INIT_COMMAND doesn't belong there. That's not whatever "init commands" but just regular SQL queries that can be merely run usual way after connect.
  2. Regarding SET NAMES particular query, you shouldn't be using it either way, as you should set encoding through DSN.

Thus, your code should be

$db=new PDO("mysql:host=localhost;dbname=...;charset=utf8","dbu...","pass");
$db->query("SET lc_time_names='de_DE'");
$db->query("whatever else SQL you have fancy to run");

Note that there shouldn't be anything like catch(PDOException $e){die("Error!");} as well

Upvotes: -5

Related Questions