Reputation: 982
controller:
<?php
require APPPATH . '/libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class User extends REST_Controller
{
function country_get()
{
$this->db->select('id,name');
$this->db->from('countries');
$sql = $this->db->get();
$result = $sql->result_array();
$this->response($result, 200);
}
}
unexpected output:
[
{
"id": "1",
"name": "Afghanistan"
},
{
"id": "2",
"name": "Albania"
},
{
"id": "3",
"name": "Algeria"
},
{
"id": "4",
"name": "American Samoa"
},
{
"id": "5",
"name": "Andorra"
}
]
expected output:
{
"Message": "Number of Country found: 5",
"Status": "Success",
"Country": [
{
"id": "1",
"name": "Afghanistan"
},
{
"id": "2",
"name": "Albania"
},
{
"id": "3",
"name": "Algeria"
},
{
"id": "4",
"name": "American Samoa"
},
{
"id": "5",
"name": "Andorra"
}
]
}
In this code I want to show number of records as I mention in my expected output. So, How can I do this? Please help me.
Thank You
Upvotes: 0
Views: 3800
Reputation: 3450
replace your function with the following code:
function country_get()
{
$this->db->select('id,name');
$this->db->from('countries');
$sql = $this->db->get();
$res = $sql->result_array();
$result['Status'] = "Success";
$result['Message'] = "Total country found ".count($res);
$result['Country'] = $res
$this->response($result, 200);
}
Upvotes: 0
Reputation: 2355
Try this, No need to use count()
CI already giving you a count in num_rows()
function country_get()
{
$this->db->select('id,name');
$this->db->from('countries');
$sql = $this->db->get();
$count = $sql->num_rows();
$result = array();
$result['Message'] = "Number of Country found: " . $count;
$result['Status'] = "Success";
$result['Country'] = $sql->result_array();
$this->response($result, 200);
}
Upvotes: 0
Reputation: 11182
Your result is already an array so use the PHP function count()
to get the length of the array:
function country_get()
{
$this->db->select('id,name');
$this->db->from('countries');
$sql = $this->db->get();
$result = $sql->result_array();
$response = [
"Message" => "Number of Country found: " . count($result),
"Status" => "Success",
"Country" => $result
];
$this->response($response, 200);
}
Upvotes: 2