• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Passing an array (or multiple values) to a Model

#1
[eluser]NateL[/eluser]
I'm trying to pass two values into a model so that I can run a query that tests against both values.

What's the best way to handle this?

I've tried these two methods:

Controller:
Code:
$myVar = $this->the_model->the_method($var1, $var2);

the_model.php
Code:
function the_method($var1, $var2){
$this->db->select('*')->
from('foo')->
where('foo1', $var1)->
where('foo2', $var2);
}
This doesn't seem to work, So I tried loading the variables up into an array - but I still got botched results

controller:
Code:
$theVars = array();
$theVars['var1'] = '1';
$theVars['var2'] = '2';

$myVar = $this->the_model->the_method($theVars);

the_model.php
Code:
function the_method($theVars){
$this->db->select('*')->
from('foo')->
where('foo1', $theVars['var1'])->
where('foo2', $theVars['var2']);
}

still not quite giving me results I'm after.

Thanks for any tips Smile

#2
[eluser]bretticus[/eluser]
From looking at your code for a sec...I assume you are calling ->get() in your models and just not showing it Smile

Shouldn't really matter how the variables get to your model methods so long as they get there. Note that Active Record will chain multiple where() calls together with `AND`. So if your query depends on an `OR`, you will need to just stick the whole `this or that` statement in the where() parameter.

That's about as much as anyone can give you without further details.

#3
[eluser]Zorancho[/eluser]
If you are taking the values from a form, i would suggest you put them into array like this for example:
Code:
<input type="text" name="user[username]" />
<input type="password" name="user[password]" />

//Then fetch them like this:
$user = $this->input->post('user');

$sql = "SELECT * FROM table WHERE username = '".$user['username']."' AND password = '".$user['password']."'";
$query = $this->db->query($sql);
But still not sure what your question is

#4
[eluser]jcavard[/eluser]
[quote author="NateL" date="1249624378"]
the_model.php
Code:
function the_method($theVars){
  $this->db->select('*')->
  from('foo')->
  where('foo1', $theVars['var1'])->
  where('foo2', $theVars['var2']);
}
[/quote]
This gives you nothing if you don't call get()

Also, you are expecting a return from that function when you do this
Code:
$myVar = $this->the_model->the_method($theVars);

so your function should at least call get() and have a 'return'
Code:
function the_method($theVars){
  $this->db->select('*');
  $this->db->from('foo');
  $this->db->where('foo1', $theVars['vars1']);
  $this->db->where('foo2', $theVars['vars2']);
  return $this->db->get(); // this line was missing
}


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.