-1

I have a simple data retrieval PHP file from Mysql and encodes in JSON string. The code below returns the result as expected

<?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();

?>

Sample Result...

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

My goal is to use the variable that was passed to PHP and based on it's name call function. I can't seem to figure out what I'm doing wrong!

<?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();

?>

Here is the output...

Error description: {"result":null}
archiver
  • 93
  • 9

2 Answers2

1

As you can see in the doc of php.net http://php.net/manual/fr/function.call-user-func.php

The function accepts a string as a parameter (see the examples).

So it should be call_user_func('Course')

Isak
  • 11
  • 2
0

Preferred way is directly go for:-

$result = Course(); 

But if you want to use call_user_func() then use like below:-

$result = call_user_func('Course'); 

It's because it take a callback as a string :-call_user_func

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98