Jeffrey Jeffrey - 1 month ago 7
JSON Question

PHP calling another PHP page for MySQL Query (returning JSON data)

I would like to find out how a PHP page calls another PHP page, which will return JSON data.

I am working with PHP (UsersView.php) files to display my contents of a website. However, I have separated the MySQL Queries in another PHP (Get_Users.php) file.

In the Get_Users.php, I will have a MySQL statement to query the database for data. It will then encode in JSON and be echo-ed out.

In the UsersView.php, I will call the Get_Users.php in order to retrieve the Users JSON data. The data will then be used to populate a "Users Table".

The thing is, I do not know how to call the "Get_Users.php" from the "UsersView.php" in order to get the data.

Part of UserView.php

$url = "get_user.php?id=" . $id;
$json = file_get_contents($url);
$result = json_decode($json, true);


I am trying to call the file which is in the same directory, but this does not seem to work.

Whole of Get_Users.php

<?php
$connection = mysqli_connect("localhost", "root", "", "bluesky");

// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}

$valid = true;

if (!isset($_GET['id'])) {
$valid = false;
$arr=array('success'=>0,'message'=>"No User ID!");
echo json_encode($arr);
}

$id = $_GET['id'];

if($valid == true){
$query = "SELECT * FROM user WHERE id = '$id'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Invalid User ID!");
echo json_encode($arr);
}
}

mysqli_close($connection);
?>

Answer

You have a couple of different ways to accomplish this:

  • You should be able to first set the actual id and then include the Get_Users.php file like this. Notice that you should not echo out the output from Get_Users.php, instead only return the encoded json data using return json_encode($arr);:

// set the id in $_GET super global
$_GET['id'] = 1;
// include the file and catch the response
$result = include_once('Get_Users.php');
  • You can also create a function that can be called from UserView.php:

// Get_Users.php
<?php
  function get_user($id) {
    // connect to and query database here
    // then return the result as json
    return json_encode($arr);
  }
?>

// In UserView.php you first include the above file and call the function
include_once('Get_Users.php');
$result = get_user(1);
  • You could also use file_get_contents(). Notice that you need to make sure so that allow_url_fopen is enabled in your php.ini file for this to work:

$result = file_get_contents('http://example.com/Get_Users.php?id=1');

To enable allow_url_fopen you need to open up your loaded configuration file and set allow_url_fopen=1 and finally restart your webserver.


  • You could also use curl to achieve the same result:

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/Get_Users.php?id=1');
$result = curl_exec($ch);
curl_close($ch);

  • An ajax request could also be made to get the result. This example uses jQuery:

$(document).ready(function() {
  $.get({
    url: 'Get_Users.php',
    data: 'id=1',
    success: function(response) {
      // response contains your json encoded data
      // in this case you **must** use echo to transfer the data from `Get_Users.php`
    }
  });
});