Reputation: 71
I have following function
function getQuery($sql,$returnType = ''){
$data = array();
$result = $this->db->query($sql);
if($result){
switch($returnType){
case 'count':
$data = $result->num_rows;
break;
case 'single':
$data = $result->fetch_assoc(); //Line 55
break;
default:
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}
}
}
if(!empty($data)) {
return $data;
}
return false;
}
When this method is executed following error is returned
Type: Error
Message: Call to undefined method CI_DB_mysqli_result::fetch_assoc()
Line Number: 55
I can't understand why the error is being shown. Please help!!!
Upvotes: 2
Views: 4805
Reputation: 1829
fetch_assoc()
is not a method of Codeignetor query builder it's actaullay method of mysqli
but you are use "Codeignetor query builder"
for single row use like
$query = $this->db->query("YOUR QUERY");
$row = $query->row();
if (isset($row))
{
echo $row->title;
echo $row->name;
echo $row->body;
}
for multiple row :
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
You have to use Below Code
function getQuery($sql,$returnType = ''){
$data = array();
$result = $this->db->query($sql);
if($result){
switch($returnType){
case 'count':
$data = $result->num_rows();
break;
case 'single':
$data = $result->row_array(); // return result as array
or
$data = $result->row(); // return result as object
break;
default:
$data = $result->result_array(); // result in array
or
$data = $result->result(); // return a objects
}
}
if(!empty($data)) {
return $data;
}
return false;
}
Upvotes: 1
Reputation: 1658
You can try this solution for your problem :
function getQuery($sql,$returnType = ''){
$data = array();
$result = $this->db->query($sql);
if($result){
switch($returnType){
case 'count':
$data = $result->num_rows;
break;
case 'single':
$data = $result->row(); // CodeIgniter return single row
break;
default:
if($result->num_rows > 0){
$data = $result->result(); // CodeIgniter return result object and you can set result_array() get array list
}
}
}
if(!empty($data)) {
return $data;
}
return false;
}
Upvotes: 0