Connection with database - PDO

1

In the course, we are manipulating database with PDO, but now in the connection part, the MYSQL_ATTR_INIT_COMMAND appeared to me and I do not quite understand what it is for, just know that the PDO instance requests this in the options. But what's the use? What exactly does she do?

    
asked by anonymous 26.07.2017 / 04:10

2 answers

3

In official documentation :

  

PDO :: MYSQL_ATTR_INIT_COMMAND (integer)

     

Command to execute when connecting to MySQL server. Will be run again when reconnecting.

     

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

That is, it is a mysql command that will run only once per connection as soon as you connect (or reconnect) to the server.

Example usage:

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

The SET NAMES 'UTF8' command will be run once whenever a new connection is started.

    
26.07.2017 / 12:25
1

charset

  

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

** Setting the 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 PDO::MYSQL_ATTR_INIT_COMMAND let's be just one that concerns the charset used by MYSQL, which will be UTF8.

    
26.07.2017 / 13:49