1

I have a table with multiple rows where I want to encode all the rows with json.

I have been looking for other question and solutions and I have tried lots of different approaches but json_encode still returns 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();

?>

output in terminal is

[]0

if I try this

$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;

output in terminal is

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

Maybe it does not send correct query?

2 Answers 2

3

$row[] = $r;

Should be

$rows[] = $r;

Sign up to request clarification or add additional context in comments.

4 Comments

how embarrassing I didnt catch that. I have changed row to rows but it still outputs []0and I can see all the rows of table in phpMyAdmin
@SpaceDust You mean $rows is empty?
@xdazz in terminal when I enter curl http://website.local/selectpictures.php it returns []0 zero is json_last_error code means no error while encoding
@SpaceDust Try to find out why $rows is empty.
0

Finally I found the answer my database connection is mysqli but my query for SELECT * is mysql all I needed to change was mysql commands to mysqli

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

gives the correct output

["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"}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.