查询改进:foreach

时间:2012-02-18 03:52:23

标签: php mysql codeigniter activerecord

我有以下模型函数,我想知道如何改进它,并在需要时拉出所需的$row,这样我就不会得到PHP错误。

我如何提取所需数据:

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

错误:

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

型号:

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;
}

3 个答案:

答案 0 :(得分:1)

应该是这样的

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

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

参见参考http://codeigniter.com/user_guide/database/active_record.html#select

要限制特定的记录集,请使用where()函数。 e.g。

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

答案 1 :(得分:0)

变化:

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

要:

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

现在,您说这会提取所有数据,但您实际上并未过滤结果。我想知道所需的数据是什么

答案 2 :(得分:0)

<?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;

}