php - 我如何使用 php 从 sql 数据库中获取我的所有用户

标签 php mysql mysqli

<分区>

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

最佳答案

它给你 1 条记录,因为你只打印 1 条记录,

如果您不在此处使用循环,使用 $row = mysqli_fetch_assoc($response); 将始终为您提供最后一行。

您需要使用 while 循环来获取所有行,例如:

<?php
$i = 0;
$result = array(); // initialize 
while($row = mysqli_fetch_assoc($response)){
    $result[$i]['name'] = $row['imie'];
    $result[$i]['surname'] = $row['nazwisko'];  // store in an array
    $i++;
}
$finalResult['osoby'] = $result; // storing as you need
$finalResult['success'] = "1"; // no idea about this but adding this also
echo json_encode($finalResult); // encode with json
?>

关于php - 我如何使用 php 从 sql 数据库中获取我的所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56870058/

相关文章:

php - 将 SQL 语句转换为 Joomla 格式时遇到问题

mysql - 检查字符串位置是否位于 mysql 中的正确位置

javascript - 如果先前的记录相同,则隐藏表上的结果

php - mysqli_fetch_assoc()需要参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

php - 如何在 Laravel 5 中处理异常和错误信息?

php - 如何使用相同的id在多个表中输入值

MySQL子查询和连接3个表

java - 无法从 JSONArray 获取 JSONObject

php - mysql/php insert into 不执行任何操作,也没有错误

php - 如何将 MySQL 时间戳转换为 d-m-yyyy