我有这个“旧式”非 PDO MySQL 查询(代码没有收紧,只是为了准确说明我的意思):
<?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++;
}
?>
我想以 PDO 形式重新转换查询(我正在学习)。我写了这个:
<?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 />';
}
?>
...在“旧”非 PDO 表单中,我只需指定列名即可捕获 ID 和标题。...但在 PDO 表单中,我必须指定 $result[0] 和 $result[1]。...如何更改 PDO 表单,以便不必显式指定(“记住”)数组的哪个成员是 ID,哪个是标题等(因为“旧”方法允许) ?