I have this "old-style" non-PDO MySQL query (the code isn't tightened up, just to show exactly what I mean):
<?php
include('db_conn.php'); //Contains the connection info.
$category = 'cars';
$q = "SELECT * FROM `photos` WHERE `category` = '$category'";
$qResult = mysql_query($q);
$Numq = mysql_numrows($qResult);
$count = 0;
while ($count < $Numq)
{
$ThisID = mysql_result($qResult,$count,"id");
$ThisCaption = mysql_result($qResult,$count,"caption");
echo '<img src="images/'.$ThisID.'.jpg" alt="" />';
echo '<br />'.$ThisCaption.'<br /><br />';
$count++;
}
?>
I'd like to re-cast the query in PDO form (which I'm just learning). I've written this:
<?php
//I've set out the connection info format in case there's anything wrong with it...
$db = new PDO('mysql:host=my_host;dbname=my_db_name;charset=UTF-8', 'db_user', 'user_password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); //I prefer to throw PHP errors.
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$category = 'cars';
$statement = $db->prepare("SELECT * FROM `photos` WHERE `category`=?");
$statement->execute(array($category));
$statement->setFetchMode(PDO::FETCH_BOTH);
while ($result = $statement->fetch()) {
//$result[0] = the ID, $result[1] = the caption...
echo '<img src="images/'.$result[0].'.jpg" alt="" />';
echo '<br />'.$result[1].'<br /><br />';
}
?>
... In the "old" non-PDO form I can capture the ID and the caption just by specifying the column name. ... but in the PDO form I have to specify $result[0] and $result[1]. ... How can I change the PDO form so that I don't have to explicitly specify ("remember") which member of the array is the ID, and which is the caption, etc (as the "old" method allows)?