How to convert query result object to string in CodeIgniter
I have the following code in my controller:
$sql = "SELECT MAX(roll) FROM student WHERE department = '".$this->db->escape_str($sdata['department'])."'";
$query = $this->db->query($sql);
There is nothing wrong. I am getting the expected value.
However, when I try to use that value somewhere else as a string, like the following:
$rolltext = substr($query->result(), 9);
print_r($rolltext);
die();
And then run the app on localhost, I get the following error:
A PHP Error was encountered
Severity: Warning
Message: substr() expects parameter 1 to be string, array given
I know that the $ rolltext variable gets the query result as an array, not a string, which is wrong in terms of the function syntax substr()
. This is why I am getting this error. My question is, how can I convert this query result to a string and perform my substr () operations on subsequent lines? I didn't find a specific solution / recommendation for such a case in the CodeIgniter User Guide, so I'm asking here.
source to share
Try the following:
$sql = "SELECT MAX(roll) as maxroll FROM student WHERE department = '".$this->db->escape_str($sdata['department'])."'";
$query = $this->db->query($sql);
//$result = $query->result(); // returns the query result as an array of objects
$result = $query->row(); // returns a single result row
$rolltext = substr( $result->maxroll, 9);
Note:
The syntax for accessing values from a query result set is:
$ result-> field_name;
where $ result is the result set and the field name is the name of the field you want to retrieve in your query.
source to share