sitepoint-the-php-anthology-2nd-edition-oct07-0066 - Mirror STISI ...

blareweyrΛογισμικό & κατασκευή λογ/κού

13 Δεκ 2013 (πριν από 3 χρόνια και 5 μήνες)

126 εμφανίσεις

















42 The PHP Anthology

sqliteConnect.php

(excerpt)

<?php $dsn = 'sqlite2:"C:
\
sqlite
\
world.db"'; try {
$dbh = new PDO($dsn); } catch (PDOException $e) {
echo 'Connection failed: ' . $e
-
>getMessage(); } ?>

And this code will let us connect to a PostgreSQL database on
the localhost:

postgreConnect.php

(excerpt)

<?php $dsn = 'pgsql:host=localhost port=5432 dbname=world user=user
'; $dsn .= 'password=secret'; try { $dbh = new PDO($dsn); } catch
(PDOE
xception $e) { echo 'Connection failed: ' . $e
-
>getMessage();
} ?>

Discussion

Notice that in all three examples above, we simply create a new
PDO object. Only the connection data for the PDO constructor
differs in each case: for the SQLite and
PostgreSQL connections,
we need just the DSN; the MySQL connection also requires
username and password arguments in order to connect to the
database.

4

4



We could have put the username and password information in the MySQL DSN,
providing a f
ull DSN, but the average user has no cause to do this when using
MySQL. It just adds unnecessary complexity to the DSN.