使用通过URL解析的字符串搜索mysql数据库

时间:2013-12-25 15:07:12

标签: php mysql codeigniter url

我正在通过rest API解析一个网址到我的model,以便从我的mysql数据库中检索数据。由于数据被解析为encoded url mysql为我的搜索查询返回zero results,因为url被解析为,

http://www.test.comindex.php/rest/resource/qstn/questionTitle/search%val

我认为mysql尝试使用值search%val搜索数据库而不解码网址。

这件事有什么工作吗?我已经在这个问题上苦苦挣扎了很长一段时间,而且我对此有点新意。 :(

Javascript解析数据

     function doViewQ(qTitle) {

        var searchQ = document.getElementById("searchQVal").value;
        searchQ = encodeURIComponent(searchQ);
        qTitle = encodeURIComponent(qTitle);
        $.ajax({
            url: '<?php echo base_url();?>index.php/rest/resource/qstn/questionTitle/' + qTitle,

            success: function(data) {

                var jsonObj = JSON.parse(data);

                alert(jsonObj);

                document.getElementById('qres').innerHTML = '<tr><td><strong><a href="javascript:doViewQ()">'+ decodeURIComponent(jsonObj[0].questionTitle) + '</a></strong></br>'+ decodeURIComponent(jsonObj[0].questionBody) + '</td></tr>' ;


            },
            type: "get"     
        });
     }

REST api控制器

    public function doGet()
    {
       // we assume the URL is constructed using name/value pairs
        $args = $this->uri->uri_to_assoc(2);
        switch ($args['resource']) {
            case 'qstn' :
                $res = $this->student->getQ($args);
                if ($res === false) {
                    show_error('Unsupported request',404);
                }
                else {
                    // assume we get back an array of data - now echo it as JSON
                    echo json_encode($res);
                }
                break;                    

            default:
                show_error('Unsupported resource',404);
                break;
        }
    }

模型从MySQL DB中恢复数据

    public function getQ($args)
{
        // use array keys as column names for db lookup
        $where = array();
        $valid_column_names = urldecode(array('questionTitle'));

        // use only those $args vals (from URL) that match col names in students table
        foreach ($valid_column_names as $key) {
            if (isset($args[$key])) {
                $where[$key] = $args[$key];
            }
        }
        if (count($where) == 0) { // stop full select on table
            return false;
        }
        $this->db->where($where);
        $result = $this->db->get('questions');
        // return the results as an array - in which each selected row appears as an array
        return $result->result_array;

    }     

1 个答案:

答案 0 :(得分:0)

我认为你需要PHP的rawurldecode()

echo rawurldecode('foo%20bar%40baz'); // foo bar@baz

PHP documentation