php - 从数据库中检索列表

标签 php mysql json

没有真正的知识,赌博仍然存在并出现问题

我发现一个脚本,其中 m able to tag people but I don 不知道如何从数据库检索列表???

<?php

  $term = isset($_GET['term']) ? $_GET['term'] : '';

  //TODO: you should retrieve this list from database

  //list of users

  $allUsers = array(
array('id' => 10 , 'title' => ' molendijk '),
array('id' => 20 , 'title' => ' rotterdam '),

    );

    $users = array();
    foreach ($allUsers as $user)
    {
if (stripos($user['title'], $term ) !== false) {
    $users[] = $user;
}
    }

    //generate output
    echo json_encode($users);

    ?>

在//TODO 行上:您应该从数据库中检索此列表 我尝试简单地完成此代码,但它不起作用

<?php
 // connect to the "tests" database
 $conn = new mysqli('127.0.0.1', 'comments', '123456', 'comments');
 // check connection
 if (mysqli_connect_errno()) {
 exit('Connect failed: '. mysqli_connect_error());
  }
  // SELECT sql query
  $sql = "SELECT * FROM `user`  ORDER BY `id` DESC"; 
   // perform the query and store the result
   $result = $conn->query($sql);
   // if the $result contains at least one row
   if ($result->num_rows > 0) {
    // output data of each row from $result
    while($row = $result->fetch_assoc()) {

//我尝试添加$row的用户列表

   $allUsers = array(
array('id' => '. $row['id']. ' , 'title' => ' '. $row['user']. ' '),
array('id' => '. $row['id']. ' , 'title' => ' '. $row['user']. ' '),

我希望有人能给我一些想法

最佳答案

代码的最后一部分是问题所在,您在创建 $allUsers 数组时试图过于紧密地复制示例代码。

在此代码中,$allUsers[] 表示将新行添加到您已有的数据中...

$allusers = array();
while($row = $result->fetch_assoc()) {
   $allUsers[] = array('id' => $row['id'], 'title' => $row['user']);
}

关于php - 从数据库中检索列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53029559/

相关文章:

php - 我可以将 PHP 扩展类、函数等放在命名空间中吗?

php - 如何使用 PHP 获取 Mysql 数据库中的最后一个字段?

MySQL 选择从 到 并显示不带标记的结果

java - 打印每个 JAX-RS 服务的 JSON 请求/响应

cURL 中 Json 未定义

c# - 调整 jsonSerializer 时区

php - 用照片创建树状图的技巧?

php - 选择值达到和超过(但只有一个超过)另一个值的记录?

java - 带$符号的sql表名

mysql - 匹配所有值 "IN"sql查询