PHPGurukul

How to use PDO to read data from the database?

Reading data from the database is not so different than inserting data, with steps 1 to 5 being almost identical while the sixth step is different.

1) Write the regular select statement and again, instead of values, put named placeholders. For example:

$sql = "SELECT * FROM users";

2) Prepare the query:

$query = $dbh -> prepare($sql);

3) Execute the query:

$query -> execute();

4) Assign the data which you pulled from the database (in the preceding step) to a variable.

$results = $query -> fetchAll(PDO::FETCH_OBJ);

Here I used the parameter PDO::FETCH_OBJ that returns the fetched data as an object. If you’d like to fetch the data in the form of an array, use: PDO::FETCH_ASSOC. 5) Make sure that you were able to retrieve the data from the database, by counting the number of records.

if($query -> rowCount() > 0){}

6) In case that the query returned at least one record, we can echo the records within a foreach loop:

if($query -> rowCount() > 0)
{
foreach($results as $result)
{
echo $result -> name . ", ";
echo $result -> city . ", ";
echo $result -> date_added;
}
}

All code together now:

$sql = "SELECT * FROM users WHERE city = :city";
$query = $dbh -> prepare($sql);
$query -> bindParam(':city', $city, PDO::PARAM_STR);
$city = "New York";
$query -> execute();
$results = $query -> fetchAll(PDO::FETCH_OBJ);
if($query -> rowCount() > 0)
{
foreach($results as $result)
{
echo $result -> name . ", ";
echo $result -> city . ", ";
echo $result -> date_added;
}
}

For localhost Database name is : pdoanuj Sql file available inside the package.

[aio_button align=”none” animation=”none” color=”red” size=”small” icon=”play” text=”Demo” target=”_blank” relationship=”dofollow” url=”http://phpgurukul.com/demos/pdo”]        [aio_button align=”none” animation=”none” color=”red” size=”small” icon=”download” text=”Download” relationship=”dofollow” url=”http://phpgurukul.com/downloads/pdo.zip”]

Anuj Kumar

This is Anuj Kumar. I’m a professional web developer with 4+ year experience. I write blogs in my free time. I love to learn new technologies and share with others.
I founded PHPGurukul in September 2015. The main aim of this website to provide PHP, Jquery, MySQL, PHP Oops and other web development tutorials.
.

Recommended Tutorials for you


Add comment

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

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.