Jess McKenzie
Jess McKenzie

Reputation: 8385

Query Improvement: foreach

I have the following model function and I was wanting to know how I could improve it and also pull the needed $row out when needed so that I dont get a PHP error.

How I am pulling the required data:

    $data['companyName'] = $this->core_model->companyDetails('coreCompanyName');

Errors:

Undefined property: stdClass::$coreContactName
Undefined property: stdClass::$coreContactEmail

Model:

function companyDetails()
{
    $this->db->select('coreCompanyName, coreContactName, coreContactEmail');

    $this->db->from('core');

    $whereData = array('coreCompanyName' => $companyName, 'coreContactName' => $companyContactName, 'coreContactEmail' => $companyContactEmail);

    $this->db->where($whereData);

    $query = $this->db->get();

    $result = '';

    if ($query->num_rows() > 0)
    {

        foreach ($query->result() as $row)
        {
            $result .= $row->coreCompanyName;
            $result .= $row->coreContactName;
            $result .= $row->coreContactEmail;
        }
    }
    return $result;
}

Upvotes: 0

Views: 110

Answers (3)

MrPHP
MrPHP

Reputation: 972

<?php

/**
 *
 * WHERE ARE : $companyName, $companyContactName, $companyContactEmail being defined ?
 * WHY return 'companyName' WHEN You are quering based on the '$companyName' ???
 * Your query wil fail with out it, that that's all your using ?
 *
 */
function companyDetails() {

    $query = $this->db->query("SELECT companyName FROM core WHERE coreCompanyName = ? AND coreContactName = ? AND coreContactEmail = ? LIMIT 1",
    array($companyName, $companyContactName, $companyContactEmail));
    return ($query->num_rows() == 1) ? $query->row()->companyName : FALSE;

}

Upvotes: 0

Mosty Mostacho
Mosty Mostacho

Reputation: 43444

Change:

$this->db->select('coreCompanyName','coreContactName','coreContactEmail');

To:

$this->db->select('coreCompanyName, coreContactName, coreContactEmail');

Now, you said this pulls all the data, but you aren't actually filtering the result. I wonder what the required data is

Upvotes: 0

Chui Tey
Chui Tey

Reputation: 5564

It should be like this

$this->db->select('coreCompanyName, coreContactName, coreContactEmail');

not

$this->db->select('coreCompanyName','coreContactName','coreContactEmail');

See reference http://codeigniter.com/user_guide/database/active_record.html#select

To limit to a specific set of records, use the where() function. e.g.

$this->db->where('companyId', $companyId);

Upvotes: 1

Related Questions