0

I have tried this code for count rows

$count = $this->db->query("select count(*) from cgdict where cg like '%".$search_data."%'");

echo $count;

and it gives me an error

Object of class CI_DB_mysqli_result could not be converted to string
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
Naveen Roy
  • 85
  • 12
  • You want that SQL injection, do you? – Thomas Weller Oct 29 '17 at 17:11
  • Possible duplicate of [mysqli : mysqli\_result could not be converted to string](https://stackoverflow.com/questions/14573134/mysqli-mysqli-result-could-not-be-converted-to-string) – Thomas Weller Oct 29 '17 at 17:13
  • 1
    you should use `$row = $this->db->query(...)->row()` anf then `$count=$row->count` you are directly assigning a result object to a field – Madhawa Priyashantha Oct 29 '17 at 17:16
  • Your query is ok. But `echo $count` is wrong. Because echo prints out a string. But `$count` is not a string. Its object.try to use print_r or var_dump to see what is $count. – Shaiful Islam Oct 29 '17 at 22:09

1 Answers1

1

Use num_rows() to count function, because $count is an array (if not null):

$query = $this->db->query("select * from cgdict where cg like '%".$search_data."%'");
$result = $query->result_array()
$num= $result ->num_rows();
echo $num;

Or

$query = $this->db->query("select count(*) as TotCount from cgdict where cg like '%".$search_data."%'");
$result = $query->result_array()

echo count($result[0]['TotCount']);

Security note

Before sending $search_data direct to SQL query, make sure you use $this->input->post to catch and clean from SQL injection.

halfer
  • 19,824
  • 17
  • 99
  • 186
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
  • I edit this by $query = $this->db->query("select * from cgdict where cg like '%".$search_data."%'"); $num= $result ->num_rows(); echo $num; – Naveen Roy Oct 30 '17 at 06:34
  • $result = $query->result_array(); not required there................... its working perfectly now... thanks.... – Naveen Roy Oct 30 '17 at 06:36
  • 1
    echo count($result[0]['TotCount']); this one was given 1 in every run... so i used first one. – Naveen Roy Oct 30 '17 at 06:37