php - How to fetch data from an Array -
hi have written class data database, , in view creating instance of class data.
everything seems working fine, when use print_r($emp_data)
in view. returns data in 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 use foreach
loop gives me error message.
warning: illegal string offset 'emp_id' in e:\xampp\htdocs\emp_management\views\view_all_employees.php on line 11
following code have written.
class method
public function get_employees(){ $query= "select * 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 $data){ echo $data['emp_id']; } ?>
kindly guide me doing wrong here. think array
not returning data in correct format.
thanks
mysqli_fetch_array
returns single row. loop (after you've called 'fetch' function) assuming have retrieved employees. correct class function like:
public function get_employees(){ $query = "select * 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 rows in array } return $data; } }
you can leave view
loop is. should work expected.
Comments
Post a Comment