Create a new PDO object.
PDO's constructor takes at most 4 parameters, DSN, username, password, and an array of driver options.
A DSN is basically a string of options that tell PDO which driver to use, and the connection details… You can look up all the options here PDO MYSQL DSN.
<?php $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password');
NOTE: If you get an error about character sets, make sure you add the charset parameter to the DSN. Adding the charset to the DSN is very important for security reasons, most examples you'll see around leave it out. MAKE SURE TO INCLUDE THE CHARSET!
You can also pass in several driver options as an array to the fourth parameters.
I recommend passing the parameter which puts PDO into exception mode, which I will explain in the next section.
The other parameter is to turn off prepare emulation which is enabled in MySQL driver by default, but really should be turned off to use PDO safely and is really only usable if you are using an old version of MySQL.
<?php $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
You can also set some attributes after PDO construction with the setAttribute method:
<?php $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);