âš ī¸ Warning âš ī¸ Deprecated Code! This video tutorial contains outdated code.
💡 If you wish to update it, any AI assistant will update the code for you in seconds.

PDO Tutorial Connect Database and Query Example

Published : January 26, 2015   •   Last Edited : November 24, 2025   •   Author : Adam Khoury
Learn how to connect to a mysql database and query it using the PDO extension in PHP. After this PDO coding exercise we conduct a mysqli vs PDO discussion that you may find informative.
<?php
try {
    $db = new PDO('mysql:host=localhost;dbname=db_name', 'db_user', 'db_password');
} catch (PDOException $e) {
    echo $e->getMessage()."<br>";
    die();
}
$sql = 'SELECT username, country from people';
foreach( $db->query($sql) as $row ) {
    echo $row['username']." - ".$row['country']."<br>";
}
$db = null;
?> 
Link to document we discussed about the PHP mysqli extension. http://php.net/manual/en/mysqli.overview.php