php - Codeigniter 选择不同的并传递变量列表

标签 php mysql codeigniter

只想从 table WHERE user_id=$user_id 中选择不同的国家/地区,将国家/地区列表从模型传递到 Controller ,然后传递国家/地区列表的 JSON 表示形式,但因为我是 Codeigniter 的新手我不确定是否正确编写了查询以及是否返回列表或单个值。您能检查一下我的代码吗?

型号:

public function did_get_country_list($user_id) {

        $this->db->distinct('country');
        $this->db->where('user_id',$user_id);
        $query = $this->db->get('table');

        if ($query->num_rows() >= 1) {
         foreach ($query->result() as $row)
        {
            $country = $row->country;
        }
        return $country;
        }
        else{
         return false;
        }       
    }   

Controller :

$country = $this->model_users->did_get_country_plans($user_id);

echo json_encode($country);

最佳答案

你的代码对我来说看起来几乎没问题,但我认为你应该更改 2 行:

1) 在实际查询之前删除对 num_rows 的检查。

2) 要返回国家/地区数组,请在 $country 末尾添加 [] 以推送新值。

所以,代替这个片段:

    if ($query->num_rows() >= 1) {
     foreach ($query->result() as $row)
    {
        $country = $row->country;
    }
    return $country;
    }
    else{
     return false;
    }

你会:

    $country = false;
    foreach ($query->result() as $row)
    {
        $country[] = $row->country;
    }
    return $country;

关于php - Codeigniter 选择不同的并传递变量列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25103077/

相关文章:

java - 后台 Chrome 浏览 session 问题

javascript - 从 jQuery 日期选择器获取查询值(格式问题)

php - 如何在wordpress中连接多个表获取数据

mysql - 使用内连接从三个不同的表中选择内容

php - Y、N和0都等于0?

php - 2 个键的数组中未定义键 1

php - MySQL/PHP : Returning the row values that contain the MAX value

php - Codeigniter 中的 Cron 职位

php - Codeigniter 根据选择的下拉列表 id 显示数据描述

php - ci : handling session in a database without update privilege