【问题标题】:sql json not workingsql json 不工作
【发布时间】:2016-04-06 17:47:54
【问题描述】:

我创建了一个 php 脚本,它从数据库中获取值并将其保存在 json 中

$sql = "SELECT detail FROM BUNK WHERE id = '".$id."'";
$sql2 = "SELECT yes FROM BUNK WHERE id = '".$id."'";
$sql3 = "SELECT depend FROM BUNK WHERE id = '".$id."'";
$sql4 = "SELECT no FROM BUNK WHERE id = '".$id."'";

$result1 = mysqli_query($link,$sql);
$json['detail'] = $result1;
echo json_encode($json);

$result2 = mysqli_query($link,$sql2);
$json['yes'] = $result2;
echo json_encode($json);

$result3 = mysqli_query($link,$sql3);
$json['depend'] = $result3;
echo json_encode($json);

$result4 = mysqli_query($link,$sql4);
$json['no'] = $result4;
echo json_encode($json);

但我得到的结果是:

{"detail":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}}{"detail":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null},"yes":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}}{"detail":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null},"yes":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null},"depend":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}}{"detail":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null},"yes":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null},"depend":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null},"no":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}}

【问题讨论】:

  • 为什么不在一个查询中完成这一切?
  • @chris85 new in phph.. :)
  • 您只能执行一个查询(SELECT detail, yes, depend, no FROM ...),然后您必须获取该查询(请参阅these examples)。最后但同样重要的是,您只需编码一次,否则您的 JSON 对象无效。
  • 非常感谢大家...!!

标签: php sql json


【解决方案1】:

基本:

$sql    = "SELECT detail, yes, depend, no FROM BUNK WHERE id = '".$id."'";
$result = mysqli_query( $link, $sql ) or die( $link->mysqli_error );
$rows   = mysqli_fetch_all( $result, MYSQLI_ASSOC );

$json   = json_encode( $rows );

这只是基本的,因为:

  1. 如果您的id 来自用户输入(即HTML 表单),您必须考虑prepared statements
  2. 如果要自定义 JSON 字符串,则必须使用带有 mysqli_fetch_assoc 的循环,而不是使用 mysqli_fetch_all

$json 是生成的 JSON 字符串。输出它:

echo $json;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多