我正在尝试构建一个非常基本的API,我有一个从MySQL视图中提取数据的查询,我可以回答查询,因为json没有问题,但我想把查询放入一个函数,以便能够从API脚本中调用它...我只是在将代码放入函数时遇到了一些麻烦。
这是有效的颂歌.....
<?php
$servername = "database.com";
$username = "username";
$password = "password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["year"]. " - " . $row["Month"]. " " . $row["the_days"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
...这是我试图把它变成一个函数(它不起作用!)......
//Connection as above
function available_dates() {
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$encodeArray = array();
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row;
}
} else {
echo "0 results";
}
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
}
available_dates();
$conn->close();
?>
我刚刚开始使用各种功能,所以我希望我的错误很滑稽! ...我需要使用echo来调用函数吗?
答案 0 :(得分:1)
你对函数的返回值一无所知。
您可以将其回显或将其放入变量中。
var myObj = GetMyObjInstance();
// Working, but apparently it's not good practise to call .scope() on an element.
myObj.onUpdated = function(){
console.log("myObj updated");
var v = myObj.getValue();
var controllerDiv = document.getElementById("controller");
var $scope = angular.element(controllerDiv).scope();
$scope.apply(function(){
$scope.someValue = v;
});
}
// Tried to do this, thinking i would get closure on the scope.
angular.module('myApp', []).controller('controller', function($scope){
myObj.onUpdated = function(){
console.log("myObj updated"); // Gets logged to console...
var v = myObj.getValue();
$scope.somevalue = v; // ... but somevalue does not get displayed.
$scope.apply(); // Error, says it's not a function, so maybe this is not the right object?.
}
});
或
echo available_dates();
或
print_r(available_dates());
答案 1 :(得分:1)
你没有返回任何东西,你应该为某些东西指定返回值。你应该像这样调用你的函数。
function available_dates() {
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$encodeArray = array();
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row;
}
} else {
echo "0 results";
}
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
}
$result=available_dates();
答案 2 :(得分:0)
您在代码中返回一个数组:
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
您应该像这样回复json_encode:
echo json_encode($encodeArray);
然后处理格式化/显示(或者,您可以像在第一个示例中那样进行回显并回显准备显示的输出):
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row["year"]. " - " . $row["Month"]. " " . row["the_days"].<br>";
}
然后
echo json_encode($encodeArray);