How to use PDO to SELECT data from MySQL using PHP example

You have a MySQL table of data in your database, you want to display it on a webpage, so it can be displayed and viewed by other people.

You need to have a few things in order to accomplish this:

  1. A MySQL database
  2. A table containing data in the above database
  3. The credentials to above (the host location, username and password)
  4. Which you can use to create a connection in your PHP page
  5. A way to iterate through the records so they can be echoed out
  6. The table field names so we can display them on the page

What if you don’t have all of the above set-up?

Don’t worry at the end will be a link to some example PHP source code along with the SQL statements to create the database and table.

PHP PDO (PHP Data Objects) makes it very easy to SELECT data from your table.

To connect to the database with PDO is very simple:

$dbh = new PDO('mysql:host=localhost;dbname='. $db_name, $db_username, $db_password);

The above line creates a connection and stores it in the $dbh variable as an object

That variable can then be used to retrieve the records using a SELECT statement:

foreach($dbh->query('SELECT * FROM makes ORDER BY make ASC') as $row) {

This allows us to use the resulting rows of data returned by the query.

Using the field names from the database table, we can output the data with an echo statement:

echo "<td>". $row['make'] ."</td>";

After we’ve finished, set the variable to null to free up the connection:

$dbh = null;

So with the above few lines of code, we can connect to the database. Retrieve the data and output it.

To make everything look good, we need a few more lines of code to create a table.

The full source code is available here on github as a simple PHP PDO Crud Demo.

The demo is a simple CRUD example of using PHP, PDO and MySQL to display a list of car makes