These different
methods are introduced next.
Embedding the Parameters into the Constructor
The easiest way to connect to a database is by simply passing the connection parameters
into the constructor. For instance, the constructor can be invoked like this
(MySQL-specific):
$dbh = new PDO("mysql:host=localhost;dbname=chp31", "webuser", "secret");
Placing the Parameters in a File
PDO utilizes PHP??™s streams feature, opening the option to place the DSN string in
a separate file that resides either locally or remotely, and reference it within the
constructor like so:
$dbh = new PDO("uri:file://usr/local/mysql.dsn");
Make sure the file is owned by the same user responsible for executing the PHP
script and possesses the necessary privileges.
Referring to the php.ini File
It??™s also possible to maintain the DSN information in the php.ini file by assigning it to
a configuration parameter named pdo.dsn.aliasname, where aliasname is a chosen
alias for the DSN that is subsequently supplied to the constructor. For instance, the
following example aliases the DSN to mysqlpdo:
[PDO]
pdo.dsn.mysqlpdo = "mysql:dbname=chp31;host=localhost"
The alias can subsequently be called by the PDO constructor like so:
$dbh = new PDO("mysqlpdo", "webuser", "secret");
Unlike the previous method, this method doesn??™t allow for the username and
password to be included in the DSN.
Using PDO??™s Connection-Related Options
There are several connection-related options for PDO that you might consider tweaking
by passing them into the driver_opts array.
Pages:
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913