以下查询只返回一个结果,即使表中有多个用user_is 2的条目。我不确定我做错了什么。
function get_payments($user_id)
{
$sql = "SELECT txn_id, payer_email FROM orders WHERE user_id = ?";
$query = $this->db->query($sql, $user_id);
//echo $this->db->last_query();
if($query->num_rows() != 0) {
foreach($query->result() as $payment)
{
$data[] = $payment;
return $data;
}
}else{
return false;
}
}
这就是$ this-> db-> last_query();回报。 SELECT txn_id, payer_email FROM orders WHERE user_id = '2'
控制器:
$profile_data['user_payments'] = $this->profile_model->get_payments($user_id);
查看:
<?php
//var_dump($user_payments);
foreach($user_payments as $payment)
{
echo '<p>';
echo $payment->txn_id;
echo $payment->payer_email;
echo '</p>';
}
?>
答案 0 :(得分:1)
试试这个:
<?php
function get_payments($user_id){
$this->db->select('txn_id, payer_email')
->from('orders')
->where('user_id', $user_id);
$qry = $this->db->get();
$res = $qry->result();
if($res){
return $res;
}else{
return false;
}
}
?>
答案 1 :(得分:0)
这里有一个小错误
foreach($query->result() as $payment)
{
$data[] = $payment;
return $data; // this line returns the data and it stops execution in first loop itself
}
它应该像
if($query->num_rows() != 0) {
foreach($query->result() as $payment)
{
$data[] = $payment;
}
return $data;
}
答案 2 :(得分:-1)
在foreach循环完成后,您应该从模型返回$data
。
if($query->num_rows() != 0) {
foreach($query->result() as $payment)
{
$data[] = $payment;
}
return $data;
}
else
{
return false;
}
答案 3 :(得分:-1)
简单CI方式:
...
$query = $this->db->query($sql, $user_id);
return $query->result_array();
不需要循环,没有。
我看到你正在使用对象形式,在这种情况下这样做:
return $query->result();
然后就像你已经在做的那样在你的视图中循环它。
所以这是整个模型方法:
function get_payments($user_id) {
$sql = "SELECT txn_id, payer_email FROM orders WHERE user_id = ?";
$query = $this->db->query($sql, $user_id);
return $query->result();
}
请参阅此处的相关文档:http://ellislab.com/codeigniter/user-guide/database/results.html
使用Active Records(对CI最“自然”):
function get_payments($user_id) {
return $this->db
->select('txn_id, payer_email')
->where('user_id', $user_id)
->get('orders')
->result();
}