Sandeep Gupta
Sandeep Gupta

Reputation: 7250

php wont let me echo JSON string

Throught an AJAX call I want to pick some data from DB and send back to client. $result is return value of SELECT QUERY

Case1:This works fine

$str = "[";
    while($row = mysqli_fetch_assoc($result)) {
          $str = $str ."{". 

                            '"Name":'. '"'. $row["Name"] . '"'  

                       . "},";
    }
}
$str = $str . "]";
echo str;

CASE2:This works fine too:

$str = "[";
    while($row = mysqli_fetch_assoc($result)) {
          $str = $str ."{". 

                            '"ID":'. '"'. $row["ID"] //SEE HERE

                       . "},";
    }
} else {
    echo "0 results";
}

$str = $str . "]";

echo $str;

CASE3: BUT FOLLOWING GIVES error with 500()

$str = "[";
    while($row = mysqli_fetch_assoc($result)) {
          $str = $str ."{". 

                            '"ID":'. '"'. $row["ID"] . '",'   //SEE HERE
                            '"Name":'. '"'. $row["Name"] . '"'


                       . "},";
    }
} else {
    echo "0 results";
}

$str = $str . "]";

echo $str;

I want to send echo str after making it in JSON format and parse it at client side using `JSON.parse(). Case1 and 2 work fine when I have only one key-value pair. But as soon as I put 2 key-value pairs I get error:

POST https://******************.php 500 ()

Upvotes: 0

Views: 85

Answers (2)

A H Bensiali
A H Bensiali

Reputation: 875

You really need to use the appropriate functions.

Get into good programming habits.

$rtn = []; //create array
while($row = mysqli_fetch_assoc($result)){
    //push result into array
    $rtn[] = ['ID'=> $row["ID"], 'Name'=> $row['Name']]; 
}

if($rtn)//if array has entries
    echo json_encode($rtn);//encodes result to json
else
    echo "0 results";

Upvotes: 3

K. Maliszewski
K. Maliszewski

Reputation: 333

It return 500, because you have error in your script. You can add below code and check where is the mistake.

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Probably in your code is missing dot. Check this:

$str = $str . "{" .

    '"ID":' . '"' . $row["ID"] . '",' .  
    '"Name":' . '"' . $row["Name"] . '"'

. "},";

Upvotes: 1

Related Questions