Welcome Guest, Not a member yet? Register   Sign In
Making queries through call_user_func_array
#1

[eluser]ilSignorCarlo[/eluser]
Hi,
I'm writing a CodeIgniter model whith some database utilities. What I'm trying to do is to write a function to create customizable queries.

The idea is to pass to the function a table name, a number (to limit results), and an optional array with parameters for the "where" clause. Inside the function I just test if the array is not empty and just in this case I use the "where" clause.

I'm pretty new to PHP and to CodeIgniter too, but I found that I can do this with the call_user_func_array function.

so I call it this way:

Code:
if (!empty($where_array)) {
     call_user_func_array(array(&$this->db, 'where'), $where_array);          
       }

The problem, I think, is that where() needs a pair of values. How can I do this?

Anyway, is what I'm trying to do a good practice?

Thanks,
Bye
#2

[eluser]TheFuzzy0ne[/eluser]
I don't fully understand why this is necessary.

Please could you post a bit more code so I can understand the context in which it appears? Also, if you can be a bit specific about what your trying to achieve, that would really help.

I can't help thinking that there's a better way to do this.
#3

[eluser]ilSignorCarlo[/eluser]
[quote author="TheFuzzy0ne" date="1240769497"]I don't fully understand why this is necessary.[/quote]

Indeed it is not really necessary.

Quote:if you can be a bit specific about what your trying to achieve, that would really help.

Code:
function get_latest($table, $limit, $where_array=array())
     {
       $this->db->orderby('Data', 'desc');

       if (!empty($where_array)) {
           call_user_func_array(array(&$this->db, 'where'), $where_array);          
       }
  
     $this->db->limit($limit);

     $query = $this->db->get($table);
    return $query->result();
     }


The where part should be something like: $this->db->where('Type', $type)
#4

[eluser]davidbehler[/eluser]
try this:
Code:
if (!empty($where_array)) {
           foreach($where_array as $key => $value)
           {
             $this->db->where($key, $value);
           }
       }




Theme © iAndrew 2016 - Forum software by © MyBB