PHP 中的函数未返回结果

function in PHP not returning result

我有一个来自 Mysql 的简单数据检索 PHP 文件,并在 JSON 字符串中进行编码。下面的代码returns 结果符合预期

<?php
require 'dbconnection.php';


$tablename = $_GET["tabname"];

$sql = "SELECT * FROM ". $tablename ;

if (!mysqli_query($conn,$sql))
{
    echo("Error description: " . mysqli_error($con));
} else {
    $res = mysqli_query($conn,$sql);
} 

$result = array();


while($row = mysqli_fetch_array($res)){
array_push($result,
array('_id'=>$row[0],
      'course_name'=>$row[1],
      'address'=>$row[2],
      'city'=>$row[3],
      'state'=>$row[4],
      'zipcode'=>$row[5],
      'phone'=>$row[6]));
}   


echo json_encode(array("result"=>$result));
$conn->close();

?>

示例结果...

{"result":[{"_id":"1","course_name":"Quail Valley","address":"12565 NW Aerts Rd.","city":"Banks","state":"OR","zipcode":"97106","phone":"5033244444"},...]}

我的目标是使用传递给 PHP 的变量并基于它的名称调用函数。我似乎无法弄清楚我做错了什么!

<?php
require 'dbconnection.php';


$tablename = $_GET["tabname"];

function Course() {
    $sql = "SELECT * FROM ". $tablename ;

    if (!mysqli_query($conn,$sql))
    {
        echo("Error description: " . mysqli_error($conn));
    } else {
    $res = mysqli_query($conn,$sql);
    }

    $results = array();

    while($row = mysqli_fetch_array($res)){
    array_push($results,
        array('_id'=>$row[0],
          'course_name'=>$row[1],
          'address'=>$row[2],
          'city'=>$row[3],
          'state'=>$row[4],
          'zipcode'=>$row[5],
          'phone'=>$row[6]));
    }
        return $results;
}

$result = call_user_func(Course()); 
// OR... $result = call_user_func($tablename());
echo json_encode(array("result"=>$result));
$conn->close();

?>

这是输出...

Error description: {"result":null}

如您在 php.net http://php.net/manual/fr/function.call-user-func.php

的文档中所见

该函数接受一个字符串作为参数(参见示例)。

所以应该是call_user_func('Course')

首选方式是直接去:-

$result = Course(); 

但是如果你想使用call_user_func()然后像下面这样使用:-

$result = call_user_func('Course'); 

这是因为它将回调作为字符串:-call_user_func