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);
Nothing wrong with it. I'm getting my expected value.
However, when I try to use this value somewhere else as a string, like the following:
$rolltext = substr($query->result(), 9);
print_r($rolltext);
die();
And then run the application in 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 variable $rolltext is getting query result in the form of an array, instead of string, which is incorrect in terms of syntax of the substr() function. That's why I'm getting this error. My question is: How can I convert this query result into a string and perform my substr() operations in the subsequent lines? I didn't find a specific solution/guideline for such case in the CodeIgniter user guide, that's why I'm asking here.
Try with 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 query resultset is :
$result->fieldname;
where $result is the resultset and fieldname is the name of the field you want the output of in your query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With