来自mySQL数据库的数据以JSON格式提供

时间:2017-04-24 17:07:52

标签: php mysql json

我想使用JSON

从数据库输出整个数据

不幸的是我在索引页面上遇到错误,说:试图获取非对象的属性.. 我已编辑了我的代码,但仍然返回错误“语法错误,意外'$ name'”。

 <?php
                include_once"model/api.php";

                $text = view_rentalsJSON();
                $adverts = json_decode($text) ;

                for ($i=0; $i < sizeof($adverts); $i++){
                    $staff = $adverts[$i]

                    $name = $staff->name ;
                    echo "Name ".$name."<br/>" ;
                }
 ?

这就是我的API函数的样子:

function view_rentalsJSON()
{
                include("controller/connection.php");
                $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
                if ($conn->connect_error) 
                {
                  die("Connection failed: " . $conn->connect_error);
                }
                $sql = "SELECT * from adverts ";
                $result = $conn->query($sql);

                $array = array();
                while($row = $result->fetch_assoc()){
                    $array[] = $row;
                }

                $json = json_encode($array);

                // close connection
                $conn -> close() ;

                //  return the resultant query
                return $json ;
}

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

There are few issues with your code, such as:

  • You're not creating JSON string in the correct way. Create an empty array $array at the beginning, and append $row array to this $array in each iteration of while loop. And after coming out of the loop, use json_encode() function to encode the resultant array $array and return it.
  • Your connection handler $conn is not available in the scope of your function. Either use global or explicitly pass the connection handler to view_rentalsJSON() function.
  • You need to close the connection before the return statement.

So your view_rentalsJSON() function should be like this:

function view_rentalsJSON($conn){
    $sql = "SELECT * from adverts";
    $result = $conn->query($sql);

    $array = array();
    while($row = $result->fetch_assoc()){
        $array[] = $row;
    }
    $json = json_encode($array);
    $conn->close();

    return $json;
}

Subsequently, assuming the fact that $conn is your connection handler, you need to change your index page code in the following way,

<?php
    include_once"model/api.php";
    $text = view_rentalsJSON($conn);
    $stafflist = json_decode($text);
    for ($i=0; $i < sizeof($stafflist); $i++){
        $staff = $stafflist[$i] ;

        $name = $staff->name ;
        echo "Name ".$name."<br/>" ;

        //$room = $staff -> room ;
        //echo "Room ".$room."<br/>"  ;

        //$telephone = $staff -> telephone ;
        //echo "telephone ".$telephone."<br/>"  ;
        //echo "<br/>" ;  
    }
?>