Database connection - PDO

Asked

Viewed 851 times

1

Guys, in the course, we are manipulating database with PDO, but now in the connection part, appeared to me the MYSQL_ATTR_INIT_COMMAND and I don’t really understand what it’s for, I just know that the PDO instance asks for it in options. But what’s it for? What exactly does it do?

2 answers

3


In the official documentation:

PDO::MYSQL_ATTR_INIT_COMMAND (integer)

Command to run when connecting to Mysql server. It will be executed again when reconnecting.

Note that this constant can only be used in the driver_options array build a new database handler.

I mean, it’s a command mysql which will run only once every connection, as soon as you connect (or reconnect) to the server.

Example of use:

$db = new PDO('mysql:dbname=mydb;host=localhost;port=3306', $user, $pass, 
    array(PDO::MYSQL_ATTR_INIT_COMMAND =>  "SET NAMES 'UTF8'")
);

The command SET NAMES 'UTF8' will run once, whenever this new connection starts.

  • Okay, Ricardo, thank you! But I’m still having doubts! I know he will run once when he connects, but, what does he do? It only serves to set the database to UTF8, etc...? Or I run what I want there?

  • @Lucascarvalho you can run any valid command.

  • Got it. Thank you Ricardo!!

1

charset

In versions prior to PHP 5.3.6, this element was ignored from silent form. The same behavior may be partially replicated with PDO::MYSQL_ATTR_INIT_COMMAND option, as well as example below demonstrates.

** Setting Character set to UTF-8 before PHP 5.3.6**

<?php
    $dsn = 'mysql:host=localhost;dbname=testdb';
    $username = 'username';
    $password = 'password';
    $options = array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
    ); 

    $dbh = new PDO($dsn, $username, $password, $options);
?>

With the PDO::MYSQL_ATTR_INIT_COMMAND we set only one that concerns the charset used by MYSQL, which will be UTF8.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.