PDO:行名称作为结果数组的索引

时间:2012-05-18 16:59:32

标签: php mysql pdo

我有这种“旧式”非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,哪个是标题等(因为“旧”方法允许) ?

3 个答案:

答案 0 :(得分:3)

您可能不想使用 PDO::FETCH_BOTH 作为抓取模式,而是希望使用 PDO::FETCH_ASSOC - 以关联方式获取数据阵列。

然后您可以通过以下方式访问数组成员:$result['id']$result['caption']等。


PDO支持几种有趣的提取模式;包括

  • associative-array:数组的键将是从数据库返回的列名;这可能是你习惯的
  • 对象;包括您指定的类的实例

要查看可能的内容,您可能需要查看不同的 PDO::FETCH_* 常量 - 列表可在此处找到:Predefined Constants

答案 1 :(得分:1)

$statement->setFetchMode(PDO::FETCH_ASSOC);

指定here

答案 2 :(得分:0)

PDO::FETCH_BOTH应该允许您作为关联数组和迭代器访问结果,以便它可以工作。您可以尝试将其更改为PDO::FETCH_ASSOC,看看是否有效,但也尝试明确说明查询中的列,而不是使用*

相关问题