【问题标题】:Error getting value from PHP with JSON使用 JSON 从 PHP 获取值时出错
【发布时间】:2016-02-15 11:49:41
【问题描述】:

我有一个包含 2 列表的数据库:ID(int),Message(text)

我需要通过以下方式获取值:

ID (select * from table where ID=1)

但是,我只得到 ID,消息显示 NULL 值(使用 JSON 解析)。

<?php 

//Getting the requested id
$ID = $_GET['ID'];

//Importing database
require_once('dbConnect.php');

//Creating sql query with where clause to get an specific employee
$sql = "SELECT * FROM T1 WHERE ID=$ID";

//getting result 
$r = mysqli_query($con,$sql);

//pushing result to an array 
$result = array();
$row = mysqli_fetch_array($r);
array_push($result,array(
        "ID"=>$row[0],
        "MESSAGE"=>$row[1],


//displaying in json format 
echo json_encode(array('result'=>$result));

mysqli_close($con);

?>

这就是我得到的:

{"result":[{"ID":"1","MESSAGE":null,}]}

【问题讨论】:

  • 这个问题没有足够的信息。您如何将查询结果解析为 JSON?您可以粘贴执行此操作的代码的 sn-p 吗?完成后,预期的结果应该是什么?
  • 我在问题中添加代码。
  • 使用 var_dump($row) 查看数组。我认为您使用 $row[1] 的列有误,请先检查一下
  • 不,是的,我也添加了其他列并全部获取,但我从未收到消息,我认为因为它有很多字符,消息的长度可以让他显示为 Null ?
  • 这甚至不是有效的 php 代码。一些)终于不见了……

标签: php json


【解决方案1】:

我为您修复了一些语法错误。其他需要改进的地方:

a) 永远不要在 sql 语句中使用原始 $_GET 数据!至少将数据转换为正确的类型(int)。查看准备好的语句以避免 sql 注入。

b) 仅当您的查询找到某些内容时,才将数据添加到 $result

<?php 

//Getting the requested id
$ID = (int) $_GET['ID']; // Cast value to int to prevent sql injection!

//Importing database
require_once('dbConnect.php');

//Creating sql query with where clause to get an specific employee
$sql = "SELECT * FROM T1 WHERE ID=$ID";

//getting result 
$r = mysqli_query($con,$sql);

//pushing result to an array 
$result = array();
if($row = mysqli_fetch_array($r)) {
  array_push(
    $result,
    array(
        "ID"=>$row[0],
        "MESSAGE"=>$row[1]
    )
  );
  //displaying in json format 
  echo json_encode(array('result'=>$result));

} else {
  // Noting found
}

mysqli_close($con);

【讨论】:

    猜你喜欢
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多