从查询中返回一个对象数组?

时间:2012-02-05 11:55:08

标签: php mysqli

我需要一个函数来返回一组服务,每个服务都包含 id name 。 我一直在查看mysqli文档,但无法验证是否存在比此更智能的解决方案:

function getServices() {
    $services = array();

    $stmt = $this->db->prepare('SELECT id, name FROM services WHERE client_id=?');
    $stmt->bind_param("i", $this->clientId);
    $stmt->execute();
    $stmt->bind_result($id, $name);
    while ($stmt->fetch()) {
        $service = array();
        $service['id'] = $id;
        $service['name'] = $name;
        $services[] = $service;
    }
    $stmt->close();

    return $services;
}

我必须自己构建生成的数组似乎有点麻烦。有没有办法让mysql使用选定的列构建数组?

2 个答案:

答案 0 :(得分:2)

我不使用mysqli,但是从inspecting the docs开始,我相信这应该可行:

$stmt = $this->db->prepare('SELECT id, name FROM services WHERE client_id=?');
$stmt->bind_param("i", $this->clientId);
$stmt->execute();

$result   = $stmt->get_result();
$services = $result->fetch_all( MYSQLI_ASSOC );

$stmt->close();

return $services;

因此使用:
1. mysqli_stmt::get_result()
2. mysqli_result::fetch_all()

适用于PHP> = 5.3.0。

答案 1 :(得分:1)

切换到PDO,您可以选择

PDOStatement::fetchAll()