【问题标题】:Retrieve specific row from database and display all the data in the specific row and send json using php从数据库中检索特定行并显示特定行中的所有数据并使用 php 发送 json
【发布时间】:2015-06-09 04:04:12
【问题描述】:

我想使用 php 和 mysqli 从数据库中检索特定行。

例如:

我想检索 userid =2 的数据行

$userid =2;

然后我使用给定的 $userid 从数据库中获取用户电子邮件、姓名、密码:

include("includes/connect.php");
$user = "SELECT * FROM account WHERE user_id = $userid " ;
$query = mysqli_query ($conn,  $user);        

while($result = mysqli_fetch_array ($query)){
      $name = $result['username'];
      $password = $result['user_password']; 
      $email = $result['user_email'];           
  }

然后我想将userid=2的用户名、密码和电子邮件以json格式发送到移动应用程序。

之后我该怎么做?

【问题讨论】:

  • 您的问题取得了进展?

标签: php mysql json mysqli header


【解决方案1】:

你需要用json_encode传递数据:

$data = array();
while($result = mysqli_fetch_array ($query)){
  $data['username'] = $result['username'];
  $data['user_password'] = $result['user_password']; 
  $data['user_email'] = $result['user_email'];           
}

echo json_encode($data);

您也可以使用mysqli_fetch_assoc 从数据库中检索 json 数据:

$row=mysqli_fetch_assoc($query)
echo json_encode($row);

More information about mysqli_fetch_assoc function.

注意,如果您确定只返回一行(在这种情况下我认为只返回一行,因为通常 user_id 是唯一的),则无需使用while

【讨论】:

    【解决方案2】:

    首先你需要添加这一行header('Content-Type: application/json'); 将您的 json 文件输出到浏览器,并查看 while 循环中的更改,然后调用函数 json_encode()

    header('Content-Type: application/json');
    
    include("includes/connect.php");
    $user = "SELECT * FROM account WHERE user_id = $userid " ;
    $query = mysqli_query ($conn,  $user);        
    
    $json = array();
    
    while($result = mysqli_fetch_array ($query)){
          $json['name'] = $result['username'];
          $json['password'] = $result['user_password']; 
          $json['email'] = $result['user_email'];           
      }
    
    echo json_encode($json);
    

    阅读微尘:

    http://php.net/manual/en/function.json-encode.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多