Saturday, July 18, 2009

PHP-PDO execute a prepared SELECT statement

Today was my first attempt to execute a prepared statement using PHP-PDO. For those of you who came late PDO stands for PHP Data Objects and lets you run an abstracted way of interacting with databases.


To find out the list of databases your PDO supports, run the following command

foreach(PDO::getAvailableDrivers() as $driver)
{
echo $driver;
}


OK, now to the topic. To execute a prepared statement with a parameter. In my case, i have taken the example of using a MYSQL database

$username = $_POST['username'];

$$db = new PDO("mysql:host=$localhost;dbname=database",'username' ,'password' );

$user_id;
$sql = 'SELECT user_id FROM Users WHERE username = ?';
try {
$stmt = $db->prepare($sql);
$stmt->execute(array($username));
while ($row = $stmt->fetch()) {
echo $row['user_id'];
}
$stmt = null;
}
catch (PDOException $e) {
print $e->getMessage();
}
$db = null;

And that's how you do it!



Thanks,
Shyam Bharath S.D.