【发布时间】:2020-09-07 15:51:07
【问题描述】:
我正在尝试以json数据类型输出语句的sql结果,但提示错误SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data,我检查了我的sql语句并尝试在sql编辑器中执行它,但我不知道为什么当我尝试在浏览器中回显它时它不起作用。
所以我有一个大的 switch 语句块,这是它的一小部分,所以基本上当我输入 http://localhost/w11/local-html/part_1/api/schedule 时,它应该通过从 URL 中获取参数来输出 json 数据类型,例如 api/schedule 和 api是arg_1 和schedule 是arg_2。
case 'api':
{
header("Content-Type: application/json");
switch ($param2) {
case 'schedule':
{
switch ($param3) {
case '':
{
try {
$sqlQuery = "SELECT room, type, title, day, time FROM sessions INNER JOIN slots ON sessions.slotsID = slots.id";
$response = new JSONRecordSet();
$response = $response->getJSONRecordSet($sqlQuery, "");
echo $response;
} catch (PDOException $e) {
echo "Connection Failed:" . $e->getMessage();
}
break;
}
default:
{
//do something
break;
}
}
break;
}
这是getJSONRecordSet的函数
class JSONRecordSet extends RecordSet {
function getJSONRecordSet($sql, $params = null) {
$queryResult = $this->getRecordSet($sql, $params);
$recordSet = $queryResult->fetchAll(PDO::FETCH_ASSOC);
$nRecords = count($recordSet);
if ($nRecords == 0) {
$status = 200;
$message = array("text" => "No records found");
$result = '[]';
}
else {
$status = 200;
$message = array("text" => "");
$result = $recordSet;
}
return json_encode(
array(
'status' => $status,
'message' => $message,
'data' => array(
"RowCount"=>$nRecords,
"Result"=>$result
)
),
JSON_PRETTY_PRINT
);
}
}
还有父类
abstract class RecordSet {
protected $conn;
protected $queryResult;
function __construct() {
$this->conn = pdoDB::getConnection();
}
function getRecordSet($sql, $params = null) {
if (is_array($params)) {
$this->queryResult = $this->conn->prepare($sql);
$this->queryResult->execute($params);
}
else {
$this->queryResult = $this->conn->query($sql);
}
return $this->queryResult;
}
}
那么,我该如何解决这个错误呢?
【问题讨论】: