首页 > 解决方案 > 如何使用 php 从 sql 数据库中获取所有用户

问题描述

In$result应该是来自数据库的所有用户,但它只需要第一人称并显示错误。

我的PHP代码:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once 'connect.php';

    $response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");

    $result = array();
    $result['osoby'] = array();

    $row = mysqli_fetch_assoc($response);

    $index['name'] = $row['imie'];
    $index['surname'] = $row['nazwisko'];

    array_push($result['osoby'], $index);
    $result['success'] = "1";

    echo json_encode($result);
}

标签: phpmysqlmysqli

解决方案


您必须循环结果数组。

$resultJson = array();
$resultJson['osoby']=array()

$query = "SELECT imie,nazwisko  FROM users";
$result = $mysql->query( $query );
if ($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
      // fetch information out of the $row..
      $resultJson['osoby'][]  = ['name' => $row['imie'], 'surname' => $row['nazwisko']];
    }

}

print json_encode($resultJson);

推荐阅读