Basic Components - DB - Connecting to a database.php 1.36 KB
Newer Older
zYne's avatar
zYne committed
1 2 3 4 5
<?php ?>
Doctrine_Db allows both PEAR-like DSN (data source name) as well as PDO like DSN as constructor parameters.
<br \><br \>
Getting an instance of Doctrine_Db using PEAR-like DSN:
<br \><br \>
6
<?php
zYne's avatar
zYne committed
7 8
$str = "<?php
// using PEAR like dsn for connecting pgsql database
9

zYne's avatar
zYne committed
10
\$dbh = new Doctrine_Db('pgsql://root:password@localhost/mydb');
11

zYne's avatar
zYne committed
12
// using PEAR like dsn for connecting mysql database
zYne's avatar
zYne committed
13

zYne's avatar
zYne committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
\$dbh = new Doctrine_Db('mysql://root:password@localhost/test');
?>";
renderCode($str);
?>
<br \><br \>
Getting an instance of Doctrine_Db using PDO-like DSN (PDO mysql driver):
<br \><br \>
<?php
$str = "<?php
\$dbh = new Doctrine_Db('mysql:host=localhost;dbname=test', 
                        \$user, \$pass);
?>";
renderCode($str);
?>
<br \><br \>
Getting an instance of Doctrine_Db using PDO-like DSN (PDO sqlite with memory tables):
<br \> <br \>
<?php
$str = "<?php
\$dbh = new Doctrine_Db('sqlite::memory:');
?>";
renderCode($str);
?>
<br \><br \>
38

zYne's avatar
zYne committed
39
Handling connection errors:
40

zYne's avatar
zYne committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
<?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() . '<br />';
   die();
}
?>";
renderCode($str);
56
?>