PHP mysqli - 从预准备语句返回一个关联数组

时间:2013-02-22 01:05:11

标签: php arrays mysqli

我正在尝试使用mysqli来准备语句,以便将变量值安全地传递给查询。所有这一切对我有用,但我遇到的问题是将结果放在一个关联数组中。 到目前为止,这是我的结构:

$query = $c->stmt_init();
$query->prepare("SELECT e._id,e.description,e.eventDate,e.eventTime,e.address,e.locationDescription,i.guestId,r.guestId IS NOT NULL AS 'RSVP-ed'  FROM eventList AS e  JOIN inviteList AS i ON e._id = i.eventId LEFT JOIN rsvpList AS r ON r.eventId = e._id AND i.guestId = r.guestId JOIN guestList AS g ON g._id = i.guestId WHERE g.groupName = ?");
$query->bind_param('s',$groupName);
if ($result = $query->execute()){
    $a  = $result->fetch_array(MYSQLI_ASSOC); // this doesn't work :/
} else{
    error_log ("Didn't work");
}

正如您所看到的,我有很多列被传回,所以我不想将它们各自绑定到变量。

最重要的是,最终目标是将json编码的关联数组传递给我的应用程序的其余部分。

我在php文档和堆栈交换中查找了这个问题,我找到了建议,但我似乎无法让它们工作。任何人都可以伸出援助之手吗?

1 个答案:

答案 0 :(得分:17)

如果你有MySql Native Driver扩展(mysqlnd),你可以使用get_result方法获取ResultSet,然后以通常的方式从中获取:

$query = $c->prepare("SELECT e._id,e.description,e.eventDate,e.eventTime,e.address,e.locationDescription,i.guestId,r.guestId IS NOT NULL AS 'RSVP-ed'  FROM eventList AS e  JOIN inviteList AS i ON e._id = i.eventId LEFT JOIN rsvpList AS r ON r.eventId = e._id AND i.guestId = r.guestId JOIN guestList AS g ON g._id = i.guestId WHERE g.groupName = ?");
$query->bind_param('s',$groupName);
$query->execute();
$result = $query->get_result();
$a  = $result->fetch_array(MYSQLI_ASSOC); // this does work :)