0

I have a PHP file which currently returns JSON in these two ways:

If an error happens, I do this:

$post_data = array('error' => "no_member_id");
echo json_encode($post_data);

and if there is no error, and I need to return data in JSON format, I do this:

if (mysql_num_rows($result) > 0 )
{
         $rows = array();
         while($r = mysql_fetch_assoc($result))
         {
             $rows[] = $r;
         }

         echo json_encode($rows);
}

But what I really need to do is return the data in a format like this:

{"result":"ok", data :[{"data1":"value1", "data2":"value2"}]}

or this:

{"result":"error", data :[{"error":"no_id"}]}

Could someone please help me understand how to do that?

Thanks!!

12
  • 1
    Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. Commented Mar 13, 2013 at 13:20
  • @AarolamaBluenk thank you. How long do you think I have before these statements stop working in my code? :) Commented Mar 13, 2013 at 13:24
  • I don't think it matters; you should switch as soon as possible. Commented Mar 13, 2013 at 13:31
  • @AarolamaBluenk of course timing matters. I can't just rewrite all my code ASAP. I am curious how much time I realistically have. Commented Mar 13, 2013 at 13:51
  • When PHP 5.5 is released and used, you will get an E_DEPRECATED notice. Commented Mar 13, 2013 at 14:05

3 Answers 3

2
echo json_encode( array( "result" => "ok", "data" => $rows ) );

instead of

echo json_encode($rows);
Sign up to request clarification or add additional context in comments.

Comments

1

first, stop using mysql built in functions. they will be deprecated.

try this:

$result = 0;
$json = array(
 'result' => 'ok',
 'data'   => array()  
);
if (mysql_num_rows($result) > 0 )
  while($r = mysql_fetch_assoc($result)) {
    $json['data'][] = $r;
  }
} else {
  $json['result'] = 'error';
  $json['data'] = array('error' => "no_member_id");
}
echo json_encode($json);

Comments

1

Just add result key with specific value in both array:

echo json_encode(array("result" => "ok", "data" : $rows));

and

echo json_encode(array("result" => "error", "data" : $post_data));

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.