数据库查询未获得定义的所有记录

时间:2012-10-11 21:44:56

标签: php codeigniter foreach

模型

    $id = $this->session->userdata('id');

    $q = $this->db->get_where('shipping_address', array('customer_id' => $id));

    if ($q->num_rows == 0)
    {
        $data['id'] = 'You dont have a shipping address saved.';

    } else {
        foreach ($q->result() as $row) 
            {
            $data['first'] = $row->firstname;
            $data['last'] = $row->lastname;
            }
    }
    return $data;

控制器

    $this->load->model('Customer_accounts');

        $customer = $this->Customer_accounts->get_customer_info();
        $ship = $this->Customer_accounts->shipping_address();

        $data = $ship + $customer;

    $this->load->view('account_dashboard/personal_information', $data);

查看

<?php foreach ($ship as $row) : ?>
    <table class="fixCap" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td><?php echo $row['firstname'] . $row['lastname']; ?></td> 
      </tr>

           . . .

      </tr>
    </table>
<?php endforeach; ?>    

的var_dump

仅显示表array中有1个的rows,但它应显示2行,其中包含已定义的customer_id

问题

无法将所有数据库data传递给foreach我做错了什么?

3 个答案:

答案 0 :(得分:1)

使用:

$data = array_merge($ship, $customer); // they will merged as one array

或者你可以这样做,如果你想要它们分开

$data = array();
$data['ship'] = $ship;
$data['customer'] = $customer;

//In the view
//ship
foreach($data['ship'] as $ship)
{
   //Ship values
}

//customer
foreach($data['customer'] as $customer)
{
   //Customer value
}

THX

答案 1 :(得分:0)

您实际上并未使用代码从数据库中提取结果。

尝试这样的事情

$ret =  $q->get()->result();

foreach($ ret as $ row) {

}

答案 2 :(得分:0)

问题发生在我的Model我用

替换了上面的代码

模型

return $this->db->get_where('shipping_address', array('customer_id' => $id))->result();

在我的

查看

#I echoed the vars as objects 
$row->firstname