簡體   English   中英

Json_encode返回Null Php / MYSQL

[英]Json_encode returns Null Php/MYSQL

我有一個包含多行的表,我想用json對所有行進行編碼。

我一直在尋找其他問題和解決方案,我嘗試了很多不同的方法,但json_encode仍然返回null

<?php
    $mysqli = new mysqli('localhost', 'root', 'password', 'testBasParmak');

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    $sth = mysql_query("SELECT * FROM pictures");
    $rows = array();
    while($r = mysql_fetch_assoc($sth)) {
        $rows[] = $r;
    }
    print json_encode($rows); 

    $error = json_last_error();
    print  $error;

$mysqli->close();

?>

終端輸出是

[]0

如果我試試這個

$sth = mysql_query("SELECT * FROM pictures");
    $rows = array("id" => $id,"name" => $name,"description" => $description,"url" => $url,"users_id" => $users_id,"users_id" => $users_id,"totalvoteup" => $totalvoteup,"totalvotedown" => $totalvotedown,"totalvoteneutral" => $totalvoteneutral);
    while($r = mysql_fetch_assoc($sth)) {
        $row[] = $r;
    }
    print json_encode($rows); 

    $error = json_last_error();
    print  $error;

終端輸出是

{"id":null,"name":null,"description":null,"url":null,"users_id":null,"totalvoteup":null,"totalvotedown":null,"totalvoteneutral":null}0

也許它沒有發送正確的查詢?

$row[] = $r;

應該

$rows[] = $r;

最后我找到了答案,我的數據庫連接是mysqli,但我對SELECT *查詢是mysql所有我需要改變的是mysql命令到mysqli

$sth = $mysqli->query("SELECT * FROM pictures");
    $rows = array();
    while($r = mysqli_fetch_assoc($sth)) {
        $rows[]=$r;
    }
    print json_encode($rows); 

給出正確的輸出

["id":"2","name":"Jess","description":"who","url":"www","users_id":"705735067","totalvoteup":"0","totalvotedown":"0","totalvoteneutral":"0"},{"id":"3","name":"Jess","description":"who","url":"www","users_id":"705735067","totalvoteup":"0","totalvotedown":"0","totalvoteneutral":"0"},{"id":"4","name":"Jess","description":"who","url":"www","users_id":"705735067","totalvoteup":"0","totalvotedown":"0","totalvoteneutral":"0"}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM