Search code examples
phpcodeignitercodeigniter-3codeigniter-query-builder

Accessing each data of the Result set i.e. $this->db->get(), on the model in Codeigniter


I have to get all the phone numbers of students from database and store in string variable with a comma in between them. I have tried the following but failed.

This is my code below :

        $toNumbersCsv="";
        $this->db->select("std_cellNo");
        $this->db->from("student");

        $queryforPhone = $this->db->get();
        //Attempt 1
        // while ($row = mysql_fetch_assoc($queryforPhone)) {
            // $toNumbersCsv .= $row['std_cellNo'].',';
        // }
        //Attempt 2
        foreach($queryforPhone as $qfp){
            $toNumbersCsv .= $qfp.',';
        }

Solution

  • Hope this will help you :

    use result() to get the record from the query also

    $toNumbersCsv = "";
    $this->db->select("std_cellNo");
    $this->db->from("student");
    $results = $this->db->get()->result();
    foreach ($results as  $row) 
    {
       $toNumbersCsv .= $row->std_cellNo.',';
    }
    echo rtrim($toNumbersCsv, ',');
    

    for more : https://www.codeigniter.com/user_guide/database/results.html