为什么json_encode返回null?

时间:2015-11-24 18:24:02

标签: php mysql mamp

我是PHP新手。我的问题是json_encode返回的空指针。我试图从mamp服务器上的mysql数据库中获取数据。我究竟做错了什么??我应该使用像utf8_encode这样的东西?我试过了,没有什么特别的事情发生这是我的代码:

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "root";
    $database = "authors";

    $db = new mysqli($servername, $username, $password, $database);

    if (!$db){
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT * FROM names";

    if ($result = mysqli_query($db, $sql)){
        $resultArray = array();
        $tempArray = array();

        while($row = $result->fetch_object()){
            $tempArray = $row;
            array_push($resultArray, $tempArray);
        }
        header('Content-type: application/json');
        print_r( $resultArray );
        $s = json_encode($resultArray);
        echo $s;
        if( $s = NULL )
        {
            echo "Nullpointer";
        }
        elseif( $s == "" )
        {
            echo "Empty string";
        }
    }

    $db->close();
?>

这是输出:

    Array
    (
    [0] => stdClass Object
        (
            [FirstName] => Johny
            [LastName] => Mielony 
        )

    [1] => stdClass Object
        (
            [FirstName] => Will
            [LastName] => Turner
        )
  )

Empty string

更新的代码:

<?php
    $servername = "localhost";
    $username = "root";
    $password = "root";
    $database = "authors";

    $db = new mysqli($servername, $username, $password, $database);

    if (!$db){
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT * FROM names";

    if ($result = mysqli_query($db, $sql)){
        $resultArray = array();
        $tempArray = array();

        while($row = $result->fetch_object()){
            $tempArray = $row;
            array_push($resultArray, $tempArray);
        }
        header('Content-type: application/json');
        print_r( $resultArray );
        $s = json_encode($resultArray);
        echo $s;
        if( $s == false )
        {
            echo "Nullpointer";
        }
        elseif( $s == "" )
        {
            echo "Empty string";
        }
        else
        {
            echo "It's gooood";
        }
    }

    $db->close();
?>

并输出:

Array
(
    [0] => stdClass Object
        (
            [FirstName] => Adrian
            [LastName] => Kaczmarek
        )

    [1] => stdClass Object
        (
            [FirstName] => Krzysztof
            [LastName] => Rózga
        )

)
Nullpointer

1 个答案:

答案 0 :(得分:1)

你可以尝试解决问题

  1. 探索错误

    echo json_last_error();
    echo json_last_error_msg();
    
  2. 使用JSON_UNESCAPED_UNICODE

    $s = json_encode($resultArray, JSON_UNESCAPED_UNICODE);