PHP – PDO select records from MySql

As Zend has announce not to support mysql_* functions in future version’s of PHP (from PHP 5.5 and onwords). So now these functions will be deprecated.  So now developers should try to use PDO or MySqli extension of  PHP. Here is a small code snippet showing how to select records from Database using PDO.

// Connect to database using PDO

$db = new PDO('mysql:host='. $host .';dbname='.$db_name_uroll, $db_username, $db_password);

//Query to database users' table
$query = "select * from users ORDER BY id DESC LIMIT 10";
 //PDO::query() returns a PDOStatement on success or false on failure.
if ($stmt = $db->query($query)){

 //If we got a PDOStatement as a return value from PDO::Query() !!!ECHO WHILE FETCHING!!! 

 while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//This loop will keep going for as many rows as the PDOStatement returns.
    echo $row['username'] . "<br />";

 //If PDO::Query returned false, then something is wrong with our query. Or connection or whatever.
 echo "Query failed.";



Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.