Murlidhar Fichadia Murlidhar Fichadia - 2 years ago 80
SQL Question

count and check json query result

I am handling three scenarios :

1) If query returns no result
2) if query returns one result
3) if query returns two or more result

This is my query :

$events = DB::table('bookings')
->join(DB::raw('(select S.event_id,sum(S.spaces) as sum_spaces from spots S group by S.event_id) d'), function($join)
$join->on('bookings.event_id', '=', 'd.event_id');
->select('bookings.event_id','', 'spots.event_date','d.sum_spaces',
DB::raw('COUNT(bookings.event_id) as tb'))

I get $events in json format like this :

[] = 0
[{"event_id":1,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"450","tb":6}] = 1
[{"event_id":1,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"100","tb":16},{"event_id":2,"name":"Yoga","event_date":"2016-05-02","sum_spaces":"450","tb":6},{"event_id":3,"name":"blah","event_date":"2016-05-02","sum_spaces":"250","tb":6}] = 3

If you see that 0,1 and 3. thats what I want to know for a given resultant query.
I need to check if the above result has how many results. How can I find this

Because this is how I am handling the scenarios :

//sets default value
else if(check if $results have one and only one result)
//Do something
//here I can handle if $events query have more than one result.

Answer Source

If I understood you correctly, you need to count() them:

$numberOfResults = count($events);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download