1

Hi i have written a class to get data from database, and in view i am creating an instance of that class to get the data.

Everything seems working fine, when i use print_r($emp_data) in my view. It returns data in the following format,

Array ( 
        [0] => 1 
        [emp_id] => 1 
        [1] => Aftab 
        [first_name] => Aftab 
        [2] => Kirmani 
        [last_name] => Kirmani 
        [3] => Male 
        [gender] => Male 
        [4] => 1 
        [added_by] => 1 
       )

but when i use foreach loop it gives me an error message.

Warning: Illegal string offset 'emp_id' in E:\xampp\htdocs\emp_management\Views\view_all_employees.php on line 11

Following is the code i have written.

Class Method

public function get_employees(){
    $query= "select * from employees";
    $query_run= mysqli_query($this->conn, $query);
    if(mysqli_num_rows($query_run) > 0){
        $data= mysqli_fetch_array($query_run);
        return $data;           
    }
}

View

<?php 

include 'header.php';

$employees= new Employees();

$emp_data= $employees->get_employees();

foreach($emp_data as $data){

    echo $data['emp_id'];

}
?>

Kindly guide me what i am doing wrong here. I think array is not returning the data in correct format.

Thanks

2
  • Is it correct your array value for $emp_data ? Commented Nov 1, 2015 at 12:52
  • Yes it is, I am filling this array from my class..but its filling this in this way Commented Nov 1, 2015 at 12:56

1 Answer 1

1

mysqli_fetch_array returns a single row. Your loop (after you've called your 'fetch' function) is assuming you have retrieved all employees. Correct your class function like:

public function get_employees(){
    $query = "select * from employees";
    $query_run = mysqli_query($this->conn, $query);
    if(mysqli_num_rows($query_run) > 0){
        $data = array();
        while ($row = mysqli_fetch_array($query_run) {
            $data[] = $row; //this puts all your rows in an array
        }
        return $data;           
    }
}

You can leave your View loop as is. It should work as expected.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.