【发布时间】:2015-01-05 17:35:11
【问题描述】:
我正在尝试使用 PHP 查询 MySQL 数据库并将结果作为 JSON 返回。我是 PHP 和 Web 开发的新手,所以我不确定自己做错了什么。我已经使用 MAMP 设置了数据库。我的参数正在打印,但我没有得到 JSON。在教程的帮助下,我已经走到了这一步。
编辑:我刚刚进入 phpMyAdmin 以确保它正常工作,当我单击 Server:localhost:8889 时,会弹出一个窗口,显示处理请求时出错。错误代码 404。
我认为这是问题所在,我只是不确定为什么它不起作用。我可能会重新安装 MAMP。
<?php
$user = 'root';
$password = 'root';
$db = 'TestDB';
$host = '127.0.0.1';
$port = '8889';
$first_name = filter_input(INPUT_GET, 'first_name');
$last_name = filter_input(INPUT_GET, 'last_name');
$membership_number = filter_input(INPUT_GET, 'membership_number');
echo $first_name;
echo $last_name;
echo $membership_number;
// Create connection
// $con = mysqli_connect("localhost", "root", "root", "TestDB");
// $con = mysqli_connect("localhost", "root", "root", "TestDB", "8889", $socket);
$link = mysqli_init();
$con = mysqli_real_connect($link, $host, $user, $password, $db, $port);
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = \'$first_name\' and LAST_NAME = \'$last_name\' and MEMBERSHIP_NUMBER = \'$membership_number\'";
$result = mysqli_query($con, $sql);
if(!$result) {
die('Query failed: ' . mysqli_error());
}
// Check for results
// if ($result = mysqli_query($con, $sql)) {
if($result) {
// If there are results, create results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
// while($row = $result->fetch_object()) {
while($row = mysqli_fetch_object($result)) {
// Add each row to the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo $tempArray;
echo $resultArray;
echo $result;
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
【问题讨论】:
-
您是否将一组结果返回到 $resultArray 中?
-
听起来好像您的
if条件从未发生过。你要回结果吗?您没有错误检查您的查询。