PDO:行名作为结果数组的索引 [英] PDO: row name as index of result array

查看:66
本文介绍了PDO:行名作为结果数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个旧式"的非PDO MySQL查询(代码并未严格化,只是为了确切显示我的意思):

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++;
}
?>

我想以PDO形式(我刚刚学习)重新发送查询.我写了这个:

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 />';
}
?>

...在旧的"非PDO表格中,我只需指定列名即可捕获ID和标题. ...但是在PDO表单中,我必须指定$ result [0]和$ result [1]. ...如何更改PDO格式,这样就不必显式指定(记住")数组的哪个成员是ID,哪个是标题,等等(如旧"方法允许的那样) ?

... 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)?

推荐答案

您可能希望使用 PDO::FETCH_ASSOC ,而不是使用 PDO::FETCH_BOTH 作为获取模式>-以关联数组的形式获取数据.

Instead of using PDO::FETCH_BOTH as fetching mode, you'll probably want to use PDO::FETCH_ASSOC -- to fetch your data as an associative array.

然后,您可以通过$result['id']$result['caption']等访问数组的成员.

Then you can access the members of the array by: $result['id'], $result['caption'], etc.


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


PDO supports several interesting fetching modes ; including

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

要查看可能的结果,您可能需要查看不同的 PDO::FETCH_* 常量-可以在此处找到列表:

To see what's possible, you might want to take a look at the different PDO::FETCH_* constants -- the list can be found here : Predefined Constants.

这篇关于PDO:行名作为结果数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆