How to connect with PDO in PHP

Answer

Connections are established by creating instances of the PDO base class. It doesn't matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).

 

Example #1 Connecting to MySQL

<?php
$dbh 
= new PDO('mysql:host=localhost;dbname=pcdsdb'$user$pass);
?>

If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().

Example #2 Handling connection errors

<?php
try {
    
$dbh = new PDO('mysql:host=localhost;dbname=pcdsdb'$user$pass);
    foreach(
$dbh->query('SELECT * from tableemp') as $row) {
        
print_r($row);
    }
    
$dbh null;
} catch (
PDOException $e) {
    print 
"Error!: " $e->getMessage() . "<br/>";
    die();
}
?>
 
 

Example #4 Persistent connections

<?php
$dbh 
= new PDO('mysql:host=localhost;dbname=test'$user$pass, array(
    
PDO::ATTR_PERSISTENT => true
));
?>

All pdo Questions

Ask your interview questions on pdo

Write Your comment or Questions if you want the answers on pdo from pdo Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---