Shaik Shaik - 4 years ago 86
MySQL Question

PHP Get multiple data from mysql in array

I am trying to get multiple columns data in a array fromate form data base like for example

[{"id":"3","category":"Name","text":"text with some data","image":"http:\/\/examole.net\/folder\/images\/category1.jpg"},{"id":"4","category":"Name","text":"text with some data","image":"http:\/\/examole.net\/folder\/images\/category1.jpg"}]


using for each statement i am not able to do it as a json response

$response = array();
if(isset($_REQUEST['action']) && $_REQUEST['action']=='test'){
$query="select * from exampledb where id='".$db->escape($_REQUEST['id'])."'";
$num= $db->num_rows($query);
if($num)
{
$rows = $db->get_results($query);

foreach($rows as $row1) {

$response['id'] = $row1['id'];
$response['category'] = $row1['category'];
$response['text'] = $row1['text'];
$response['image'] = $row1['image'];
}
}
else{
$response['message']='No user Found';
$response['status']='fail';
}

}

Answer Source

after your else

else{
            $response['message']='No user Found';
            $response['status']='fail';
        }

echo json_encode($response) //<---- here convert array to json text

PHP json_encode

UPDATE

foreach($rows as $k=>$row1) { //add index $k to use an automatic autoincrement for the key
//and put it inside each fields
                $response[$k]['id'] = $row1['id'];
                $response[$k]['category'][] = $row1['category'];
                $response[$k]['text'] = $row1['text'];
                $response[$k]['image'] = $row1['image'];
            }   
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download