Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert query result object into 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);

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.

like image 727
Choudhury Saadmaan Mahmid Avatar asked Feb 01 '26 06:02

Choudhury Saadmaan Mahmid


1 Answers

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.

like image 124
Jenz Avatar answered Feb 02 '26 20:02

Jenz