从纯php进行查询以查询CodeIgniter

时间:2016-10-21 02:05:44

标签: php mysql codeigniter

我已经学习了CodeIgniter,但我在将纯php查询转换为查询CodeIgniter时遇到了困难,如何在CodeIgniter中修复我的查询?

此查询使用Codeigniter

public function get_kal($id) {
    $query = $this->db
            ->select('myname as name')
            ->from('mytable')
            ->where('myname', $id)
            ->like('%%%s%%')
            ->order_by('myname','ASC');
            ->get("q");

    $arr = array();

    $rs = mysql_query($query);

    while($obj = mysql_fetch_object($rs))
    {
        $arr[] = $obj;
    }

    echo json_encode($arr);     
}

此查询使用纯php

public function get_name($id) { 
        $query = sprintf("SELECT  myname as name from mytable WHERE myname LIKE '%%%s%%' ORDER BY myname DESC ", mysql_real_escape_string($_GET["q"]));
        $arr = array();
        $rs = mysql_query($query);

        while($obj = mysql_fetch_object($rs))
        {
            $arr[] = $obj;
        }

        echo json_encode($arr); 
    }

3 个答案:

答案 0 :(得分:1)

您可以使用

直接查询
$this->db->query('YOUR QUERY HERE');

您还可以构建查询

$query = $this->db
            ->select('myname as name')
            ->from('mytable')
            ->like('myname', $this->input->get('q', TRUE))
            ->order_by('myname','ASC');

以下是Official Doc

答案 1 :(得分:0)

$query = $this->db->query($SQL);
echo json_encode($query->result_array());

答案 2 :(得分:0)

您也可以使用以下格式。
1.多重结果
2.单一结果

1. $q = $this->db->query('MYSQL QUERY');
echo json_encode($q->result_array());


2.$q = $this->db->query('MYSQL QUERY');
echo json_encode($q->row_array());