PDO Tutorial Connect Database and Query Example

Published :
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