使用 JSON 从 PHP 获取值时出错
Error getting value from PHP with JSON
我有一个数据库 table 有 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,}]}
我为您修复了一些语法错误。其他需要改进的地方:
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);
我有一个数据库 table 有 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,}]}
我为您修复了一些语法错误。其他需要改进的地方:
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);