Jess McKenzie
Jess McKenzie

Reputation: 8385

Database Query showing in view and not $data

The below code seems to be showing in the "view" and not via $data as it should be (I have not echoed the $data['companyName'] into my view yet but $data['pageTitle'] works fine).

Issue:

enter image description here

Model:

function companyName()
    {
        $companyName = $this->db->query("SELECT company_name FROM core");

        if ($companyName->num_rows() > 0)
        {
            foreach ($companyName->result() as $row)
            {
                echo $row->company_name;
            }
        }

Controller:

public function index()
{
    $data['companyName'] = $this->core_model->companyName();
    $data['pageTitle'] = "Admin Login";
    $this->load->view('admin/assets/header', $data);
    $this->load->view('admin/login.php');
    $this->load->view('admin/assets/footer');
}

Upvotes: 0

Views: 30

Answers (1)

Joe
Joe

Reputation: 15802

By echoing something in the model, that echo happens when the model is processed, which is way before the view is even a twinkle in its controller's eye.

Instead, you should do something like this in your model:

function companyName()
{
    $companyName = $this->db->query("SELECT company_name FROM core");

    if ($companyName->num_rows() > 0)
    {
        $company_names = '';
        foreach ($companyName->result() as $row)
        {
            $company_names .= $row->company_name;
        }
    }
    return $company_names;
}

Then you can pass $data into the view and the string will be ready to echo out like you want.

Upvotes: 2

Related Questions