【发布时间】:2016-08-18 06:58:58
【问题描述】:
如何通过 JSON 对象从 MySQL 数据库中获取多个表行到应用程序中。
从表格中获取一行对我来说效果很好!但我无法获得多行,它会抛出一个错误,提示“SyntaxError: Unexpected token { in JSON at position...”
我如何实现这一点请帮助我!
这是我的角度代码..(这里我传递一个变量并获取匹配的行并将它们发送到控制台。)
$scope.companySelected = function(emp_Comp){
console.log('Selected Item is : '+ emp_Comp);
$http({
method: 'GET',
url: 'http://localhost/companyPopulate.php',
params: {employeeCompany : emp_Comp}
}).then(function successCallback(response) {
$scope.data = response.records;
console.log('success :'+ JSON.stringify(response));
//console.log(testdata.data);
}, function errorCallback(response) {
//console.log('error',response);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
这是我的 PhP 脚本...
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
//http://stackoverflow.com/questions/18382740/cors-not-working-php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
include_once 'config.php';
//create connection
$conn = new mysqli($mysql_host, $mysql_user, $mysql_password,$mysql_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$fields = array();
if(isset($_GET['employeeNo']))
$fields['employeeNo'] = $_GET['employeeNo'];
if(isset($_GET['employeeName']))
$fields['employeeName'] = $_GET['employeeName'];
if(isset($_GET['employeeCompany']))
$fields['employeeCompany'] = $_GET['employeeCompany'];
$sql = "SELECT employeeName,employeeNo FROM employee_info WHERE ";
$count = 0;
foreach($fields as $key => $value){
if($count == 0)
$sql .= $key . "='" . $value . "' ";
else
$sql .= "AND " . $key . "='" . $value . "' ";
$count++;
}
$fields = array();
$result = $conn->query($sql);
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
if ($outp != "")
{
$outp .= ",";
}
$outp .= '{"employeeName":"' . $rs["employeeName"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo $outp;
/* }else{
echo 'parameters expected from the client are missing! :) ';
} */
?>
当我在浏览器中单独运行脚本时,我得到了正确的结果。
请帮帮我!! 提前致谢!!
【问题讨论】:
-
使用 Joins 从多个表中获取数据
-
你登录成功的反应是什么?
标签: php html mysql angularjs json