Working with objects - Component overview - Db - Connecting to a database.php 1.22 KB
Newer Older
1

hansbrix's avatar
hansbrix committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
Doctrine_Db allows both PEAR-like DSN (data source name) as well as PDO like DSN as constructor parameters.



Getting an instance of Doctrine_Db using PEAR-like DSN:



<?php
$str = "<?php
// using PEAR like dsn for connecting pgsql database

\$dbh = new Doctrine_Db('pgsql://root:password@localhost/mydb');

// using PEAR like dsn for connecting mysql database

\$dbh = new Doctrine_Db('mysql://root:password@localhost/test');
?>";
renderCode($str);
?>



Getting an instance of Doctrine_Db using PDO-like DSN (PDO mysql driver):



<?php
$str = "<?php
\$dbh = new Doctrine_Db('mysql:host=localhost;dbname=test', 
                        \$user, \$pass);
?>";
renderCode($str);
?>



Getting an instance of Doctrine_Db using PDO-like DSN (PDO sqlite with memory tables):

 

<?php
$str = "<?php
\$dbh = new Doctrine_Db('sqlite::memory:');
?>";
renderCode($str);
?>




Handling connection errors:

<?php
$str = "<?php
try {
   \$dbh = new Doctrine_Db('mysql:host=localhost;dbname=test', 
                           \$user, \$pass);
   foreach (\$dbh->query('SELECT * FROM foo') as \$row) {
     print_r(\$row);
   }
   \$dbh = null;
} catch (PDOException \$e) {
   print 'Error!: ' . \$e->getMessage() . '
';
   die();
}
?>";
renderCode($str);
?>