YaohanCZ
YaohanCZ

Reputation: 29

PHP bind_result and fetch multiple rows (array)

I'm fairly new to php and mysql. I'm trying to create a rest api from php, and because my server doesn't have mysqlndinstalled, I have to use bind_result and fetch.

$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;
}

Above code works but it can only return 1 line of information at a time.

For example if the statement return:

a    b    c
1   test  test
1   test1 test1

it only returns

a: 1
b: test1
c: test1

where its supposed to be:

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

Upvotes: 1

Views: 1417

Answers (1)

Kevin
Kevin

Reputation: 41885

You're overwritting them, you could do something like this instead:

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

Or directly appending them with another dimension:

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

Upvotes: 1

Related Questions