PHP bind_result并获取多行(数组)

时间:2014-10-19 04:43:30

标签: php mysql

我对php和mysql相当新。我试图从php创建一个rest api,因为我的服务器没有安装mysqlnd,我必须使用bind_resultfetch

$stmt = $this->conn->prepare("SELECT * from d WHERE d.id = ?");
$stmt->bind_param("i", 1);
if($stmt->execute()){
    $stmt->bind_result($a, $b, $c);
    $detail = array();  
    while($stmt->fetch()){      

        $detail["a"] = $a;
        $detail["b"] = $b;
        $detail["c"] = $c;
    }

    $stmt->close();
    return $response;
} else {
    return NULL;
}

以上代码有效,但一次只能返回1行信息。

例如,如果语句返回:

a    b    c
1   test  test
1   test1 test1

它只返回

a: 1
b: test1
c: test1

应该是:

{
    a: 1
    b: test
    c: test
},
{
    a: 1
    b: test1
    c: test1
}

1 个答案:

答案 0 :(得分:1)

你正在覆盖它们,你可以做这样的事情:

$detail = array();  
while($stmt->fetch())
{           
    $temp = array():
    $temp["a"] = $a;
    $temp["b"] = $b;
    $temp["c"] = $c;
    $detail[] = $temp;
}

或者直接将它们添加到另一个维度:

$detail = array();  
while($stmt->fetch()) {           
    $detail[] = array('a' => $a, 'b' => $b, 'c' => $c);
      //   ^ add another dimension
}