doutao4938 2016-10-08 11:44
浏览 22
已采纳

PHP为MySQL Query调用另一个PHP页面(返回JSON数据)

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);
?>
  • 写回答

2条回答 默认 最新

  • duanji4449 2016-10-08 12:24
    关注

    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`
        }
      });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题