0

In my table I have two rows but when I print_r the $data that this model function is connected to it is only returning the second row in the db why?

Model Function:

function getAllUsers()
{
    $query = $this->db->get('users');

    foreach($query->result_array() as $row)
    {
        $row['id'];
        $row['fName'];
        $row['lName'];
        $row['email'];
        $row['password'];
    }

    return $row;
}

1 Answer 1

4

Because $row is the loop variable, it will only hold the data from the last iteration after the loop has exited.

Do it like this:

function getAllUsers()
{
    $rows = array(); //will hold all results
    $query = $this->db->get('users');

    foreach($query->result_array() as $row)
    {    
        $rows[] = $row; //add the fetched result to the result array;
    }

   return $rows; // returning rows, not row
}

In your controller:

$data['users'] = $this->yourModel->getAllUsers();
$this->load->view('yourView',$data);

In your view

//in your view, $users is an array. Iterate over it

<?php foreach($users as $user) : ?>

<p> Your first name is <?= $user['fName'] ?> </p>

<?php endforeach; ?>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, How would I fetch the data from the view? Before I had $data['blah'] = model_function then in the view I had $blah['table_name']
Thanks @xbonez When using it with html whats the correct syntax for when you use <?php foreach($userDetails as $userDetail):?>

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.