Oj Obasi
Oj Obasi

I am also and will continue to be a student of web design and development. My tutorials may not be for you. If you feel that way, then search online for better tutorials.

PHP PDO SELECT Data from MySQL

We have some data in our database table 'products'. We want to get each row with columns 'product_name', 'category', 'price' and 'date_added'.

First , we make sure to establish connection to our database(require 'database.php').

Now we do a simple sql SELECT with a PDO query().

<?php
require 'database.php';
try{
$sql = $db->query("SELECT product_name, category, price, date_added FROM products");
// set the resulting array to associative
$result = $sql->fetchAll(PDO::FETCH_ASSOC);
//var_dump($result);
foreach ($result as $row) {
print $row['product_name'] . "|\t";
print $row['category'] . "|\t";
print $row['price'] . "|\t";
print $row['date_added'] . "<br>";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

We set our data to an associative array($result) since we are returning more than one row of data.

To display each product with its product_name, category, price and data_added, we will be using a 'foreach construct'. This iterates through our array($result) and assigns the values of each row to '$row'.

Select using Prepared Statements

Using prepared statements, the filtering is all done for you and the chance for an Injection is very low as long as it is used properly.
<?php
require 'database.php';
try{
$sql = $db->prepare("SELECT product_name, category, price, date_added FROM products");
$sql->execute();
// set the resulting array to associative
$result = $sql->fetchAll(PDO::FETCH_ASSOC);
//var_dump($result);
foreach ($result as $row) {
print $row['product_name'] . "|\t";
print $row['category'] . "|\t";
print $row['price'] . "|\t";
print $row['date_added'] . "<br>";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>