使用JSON从PHP获取值时出错

时间:2016-02-15 11:49:42

标签: php json

我的数据库有一个包含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);

&GT;

这就是我得到的:

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

1 个答案:

答案 0 :(得分:0)

我为您修复了语法错误。其他需要改进的事情:

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