Friday, November 12

PHP: Fetch Data from a Table using PDO

Here we are, connected to the database. Woo hoo! But what good is that if we can’t
get anything out of the database? PDO provides a couple of ways for us to interact with the database.


$category = 'fruit';
$dsn = 'mysql:host=localhost;dbname=test;';
$user = 'root';
$password = '';

try
{
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'Select * from test_table where category =' . $dbh->quote($category);
foreach ($dbh->query($sql) as $row)
{
print $row['name'] . "\t";
print $row['category'] . "\n";

}
}
catch (PDOException $e)
{
echo 'PDO Exception Caught. ';
echo 'Error with the database:
';
echo 'SQL Query: ', $sql;
echo 'Error: ' . $e->getMessage();
}


download source code here.

No comments:

Post a Comment

Pencarian Google