【问题标题】:Function not returning all database rows函数不返回所有数据库行
【发布时间】:2015-12-27 19:46:38
【问题描述】:

我在 Code igniter PHP 中有这个函数,我试图从数据库中获取与输入值匹配的所有行。 我应该如何更改代码以获取与我的搜索条件匹配的所有行?

谢谢

型号搜索功能:

function findquestion($searchvalue){

        $this->db->where('answer1', $searchvalue);
        $res = $this->db->get('questions');
        $count = $res->num_rows();

        if($res->num_rows()==0){
            return "...";
        }
        $moviearray = $res->row_array();
        return $moviearray;
    }

控制器功能:

public function getdatabasedata()
    {

        if($this->input->server('REQUEST_METHOD') == 'GET')
        {
            $year = $this->input->get('searchvalue');
            if($year != ''){
                $movie = $this->adminmodel->findquestion($year);
                echo json_encode($movie);
            } 
        }
}

当我查看 Postman 以检查 JSON 对象包含什么时,这就是我得到的。但事实上,我的数据库中还有三行符合我的搜索条件。

{
  "id": "10",
  "question": "test questions",
  "image": "test image",
  "answer1": "answer1",
  "answer2": "answer2",
  "answer3": "answer3",
  "answer4": "answer4"
}

【问题讨论】:

  • 你需要遍历$res中的所有结果。
  • @jeroen 并将它们存储在数组中?
  • 是的,然后从方法中发回。
  • @jeroen 如果我在另一个函数中以 JSON 格式对数组进行编码,是否正确?
  • 使用 $this->db->like('answer1', $searchvalue);而不是 $this->db->where('answer1', $searchvalue);

标签: php json database codeigniter


【解决方案1】:
function findquestion($searchvalue){

1) 定义数组。

        $data = array(); 
        $this->db->where('answer1', $searchvalue);
        $res = $this->db->get('questions');


        if($res->num_rows()==0){
            return "...";
        }

2) 循环遍历结果并存储在数组中。

        foreach ($res->result() as $row)
            {
                $data[] = array(
                    'id' => $row->id,
                    'question'  => $row->question,
                    'image'  => $row->image,
                    'answer1'  => $row->answer1,
                    'answer2'  => $row->answer2,
                    'answer3'  => $row->answer3,
                    'answer4'  => $row->answer4
                );
            }
        //$moviearray = $res->row_array();
        return $data;
    }

【讨论】:

  • 你可以只json_encode整个result_array,在代码中保存自己的行。
猜你喜欢
  • 2019-10-11
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2017-08-28
  • 2021-04-11
  • 1970-01-01
相关资源
最近更新 更多