3

I have a script I wrote to return records for cases out of the database. I am returning one record for my mysql query when there are actually two records. This is what I am returning:

{ "cases": [ {"name":"Test Case for App","number":"3846"}] } 

I should see:

{ "cases": [ {"name":"Test Case for App","number": "2903"}, {"name":"Test Case 2","number": "2856"} ] }

Here is my source:

$sql = "select * from cases as c join contacts_cases as conc on c.id = conc.case_id where conc.contact_id = '1b360507'";
$query = mysql_query($sql);  

// If we find a match, create an array of data, json_encode it and echo it out  
if (mysql_num_rows($query) > 0)  
{  
    $row = mysql_fetch_assoc($query);  
    $response = array(  
        'name' => $row['name'],  
        'number' => $row['case_number']
    );  

    echo '{ "cases": [ ',  json_encode($response), "] }";
1
  • 2
    You might want to use a loop there to grab all the values. Commented Jul 12, 2012 at 17:34

2 Answers 2

6

If you are expecting more than one result you should try

if (mysql_num_rows($query) > 0)  
{  
    $responses = array();
    while($row = mysql_fetch_assoc($query)) {
        $responses[] = array(  
            'name' => $row['name'],  
            'number' => $row['case_number']
        );  
    }
    echo '{"cases": ' . json_encode($responses) . '}';
}
Sign up to request clarification or add additional context in comments.

Comments

2

You need to loop through all the rows, you're just getting one.

Also, don't try to build the JSON yourself. Make the array how you want then json_encode the entire thing.

$cases = array();
while ($row = mysql_fetch_assoc($query)) {
    $cases[] = array(  
        'name'   => $row['name'],  
        'number' => $row['case_number']
    );
}

echo json_encode(array('cases' => $cases));

1 Comment

@hakre: Thanks for cleaning my code. I'm starting to run out of caffeine.

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.