MySQLi结果到数组

时间:2018-02-04 09:24:37

标签: php arrays web mysqli

所以目前我的代码输出1个数组,它不会全部显示。我知道我需要一个while或foreach循环来显示其余部分。

这是我目前的代码:

    /**
 * Get work orders via email and password and institution id
 */
public function getWorkOrdersByInstitution($email, $password, $institution_id) {

    $work_order_stmt = $this->conn->prepare("SELECT * FROM project WHERE institution_id = ?");

    $work_order_stmt->bind_param("s", $institution_id);

    if ($work_order_stmt->execute()) {
        $workorder = $work_order_stmt->get_result()->fetch_assoc();
        $work_order_stmt->close();

       return $workorder;

    } else {
        return NULL;
    }
}

我希望它返回数组。目前这是返回(注意:我在显示数组时使用json_encode)

{"project_id":1,"date":"Undefined","project_code":"ea60f6190c","title":"test","description":"test","demo_url":null,"project_category_id":null,"client_id":null,"company_id":null,"staffs":"4,5,","budget":0,"timer_status":0,"timer_starting_timestamp":null,"total_time_spent":0,"progress_status":null,"timestamp_start":"1516874400","timestamp_end":"1516878000","project_status":1,"project_note":null,"institution_id":12,"project_state":2,"strata_manager":6,"site_contact":7,"place_of_service":18}

所以最终,我希望所有行都存储在一个数组中,我可以返回并在另一个页面上使用。

提前致谢。

1 个答案:

答案 0 :(得分:0)

是的,您可以使用循环来获取所有结果:

if ($work_order_stmt->execute()) {
    $result = $work_order_stmt->get_result() ;

    $workorders = [] ;
    while ($workorder = $result->fetch_assoc()) {
        $workorders[] = $workorder ;
    }
    $work_order_stmt->close();

   return $workorders;
}
else { .. }

或者您可以使用fetch_all()获取所有数据:

$workorders = $result->fetch_all();