Collecting more than one record from table

PHP PDO & MYsQL WE can collect more than one record from a table by using sql query. For example list of all states of USA from the country list. Our table have two columns one is country and other is associated states.

Displaying records from sample tables using SELECT query in PHP MySQL using PDO functions

We have already connected to database by using PDO. After successful connection to MySQL database we can use this script to display records from the table.
require "config.php";// database connection

$sql="SELECT * FROM student ORDER BY mark DESC ";
echo "<table><tr><th>ID</th><th>Name</th>
foreach($dbo->query($sql) as $row){
echo "<tr><td>$row[id]</td><td>$row[name]</td>
echo "</table>";

Adding Bootstrap style

Learn more about Bootstrap here

$sql="select state from table_name WHERE state='USA'";

echo "<table class='table table-striped'>
<tr class='info'><th>State</th> </tr>";

foreach ($dbo->query($sql) as $row) {
echo "<tr  ><td>$row[state]</td></tr>";
echo "</table>";

Displaying Multiple columns of a table

We can display more than one column of the database table. Here we will keep column name in table header and keep the record data in normal table cell.
require "config.php";// database connection
$count="select * from pdo_admin where name='$name'"; echo "<table>"; echo "<tr><th>id</th><th>userid</th> <th>password</th><th>name</th><th>status</th></tr>"; foreach ($dbo->query($count) as $row) { echo "<tr><td>$row[id]</td><td>$row[userid]</td> <td>$row[password]</td><td>$row[name]</td><td>$row[status]</td></tr>"; } echo "</table>";

Displaying date in format

SELECT date_format( dt, '%m/%d/%Y %T' ) as my_date FROM dt_tb

Precaution while passing variables to a query

When we receive a variable from a web-form or from query string or from other un-known sources , it is better to use bindParam to check and use the variable inside query.
Example of Parameterized Query using PDO
Example of SQL code Injection through Parameter

We have displayed limited number of records here , but there may be hundred or more records in a table. Displaying all in a single page will not give better user experience. We can break the total records and display limited records and then give user choice to browse to different section of the records.

This is called paging of records.
Paging of records
Download Zip file to test your PHP PDO script
PDO References Collecting single record from table
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer