0

I am fetching records from php & saving them in associative arrays. i want to create a json format like this

{
"contacts": [
    {
            "qid": "c201",
            "question": "what is your name?,

    },
    {
            "qid": "c202",
            "question": "what is your age?

    },
   ]}

I am using following code to get the data in php

 <?
$response = array();
require("dbconfig.php");
$sql_get = 'SELECT qquesid,question FROM qhistory_data';
$retval = mysql_query( $sql_get, $conn );
if(!$retval )
{

            $response["success"] = 0;
            $response["message"]= mysql_error();
            echo json_encode($response);
}
else
{

$num_rows=mysql_num_rows($retval);
if($num_rows>=0)
    {
        $i=0;
    while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
        {
            $result_array[]= $row['question'];
            $result_id[]=$row['qquesid'];

        } 
5
  • What is your question? Commented Jan 31, 2015 at 11:52
  • 1
    how about json_encode !?!? Commented Jan 31, 2015 at 11:52
  • You're json_encoding the response if there are no records, so why not json_encode the response when there are? Commented Jan 31, 2015 at 11:53
  • I am having two arrays $result_array,$result_id i want to create a json response like i have mentioned Commented Jan 31, 2015 at 11:54
  • I am not able to get the mentioned json format.I want the response like i have mentioned?@mark baker Commented Jan 31, 2015 at 11:55

1 Answer 1

1

If you want to get the array in the form you mention, you have to parse it accordingly before doing the json_encode:

$result = array("contacts" => array());
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
    $result["contacts"][]= array("qid" => $row['qquesid'], "question" =>$row['question']);
}

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

1 Comment

question id strats from 2 but it should start from 1.first record is missing

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.