ASSOC的关联数组值

ASSOC的关联数组值

本文介绍了引用来自PDO :: FETCH_ASSOC的关联数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用PDO时遇到了一个非常基本的问题,我需要一些帮助-可能我在某处遇到语法错误,但我终生找不到它(我对PDO并不熟悉,还没有使用关联数组,因此请重点关注这部分代码!)

Im having a very basic problem using PDO and i need some help - chances are I have a syntax error somewhere but i cant for the life of me find it (im new to PDO and havent used associative arrays very much so focus on this part of the code!)

我正在使用以下代码从数据库中选择与具有特定电子邮件地址的用户相关联的所有数据:

I am selecting all the data from my database associated with a user with a certain email address using the following code:

$id = '[email protected]';


$stmt = $db->prepare('SELECT * FROM first_page WHERE email=?');
$stmt->bindValue(1, $id, PDO::PARAM_STR);
$stmt->execute();
$resulty = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($resulty);
echo $resulty['title'];

print_r完整显示关联数组,但是echo不显示标题"列的存储值.数据库中有一个 列,名称为"title",因此我认为自己没有正确地引用它.但是,它看起来与我前面一本书中的示例几乎相同,因此我不知道从哪里开始寻找!

the print_r displays the associative array in its entirety, but the echo doesnt show the stored value for the column 'title'. There is a column called 'title' in the database, so im presuming im referencing it incorrectly. However it looks near identical to an example I have in a book in front of me so I dont know where to start looking!

print_r输出为:

The print_r output is:

Array ( [0] => Array ( [user_id] => 93 [time_stamp] => 2014-03-04 22:00:16 [title] => Mr [first_name] => Pete [surname] => John [phone] => 2147483647 [email] => [email protected]))

推荐答案

$stmt->fetchAll()返回关联数组的数组,因为它支持返回多于一行的数据.

$stmt->fetchAll() returns an array of associative arrays, because it supports returning more than one row worth of data.

即使结果集只有一行,fetchAll()仍会返回一个元素的数组,这是该行的关联数组.

Even if your result set has one row, fetchAll() still returns an array of one element, which is the associative array for the one row.

所以您需要:

echo $resulty[0]['title'];

这篇关于引用来自PDO :: FETCH_ASSOC的关联数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 06:57