Welcome Guest, Not a member yet? Register   Sign In
Using activerecords where clause with occasional 'OR' match
#1

[eluser]Andy UK[/eluser]
Hi guys,

I have a form that returns a value in a variable which is matched to a field in one of the database tables. The variable value is either '1' or '2' depending on the users choice. All pretty simple so far... I just use the following activerecord syntax:

$this->db->where('status', $variable);

What I want is to be able to have a third option for the user which returns fields that match either value, ie. '1' OR '2'.

Can someone help me with a simple way to do this? I tried passing the variable value of '*', but that doesn't seem to be acceptable.

Thanks!
#2

[eluser]Akinzekeel[/eluser]
First option would be the or_where() function which is used like this:

Code:
$this->db->where("status", 1);
$this->db->or_where("status", 2);

Second option: Alternatively, if your select box shows something like "all" (basically meaning do not use where) you could also do something like this:

Code:
if($this->input->post("status") != "all") {
    $this->db->where("status", $this->input->post("status"));
}
#3

[eluser]Andy UK[/eluser]
Thanks!

I used the second option and it works fine. I couldn't see the first option working as the variable will hold the same value for the where and for the or_where, eg.

User chooses 1:

Code:
$this->db->where("status", 1);
$this->db->or_where("status", 1);

User chooses 2:

Code:
$this->db->where("status", 2);
$this->db->or_where("status", 2);

User chooses ALL

Code:
$this->db->where("status", ALL);
$this->db->or_where("status", ALL);


Anyway, thanks for the help. As I said before, the second options works just fine!
#4

[eluser]juanvillegas[/eluser]
Better than that would be just using a 0 (or some integer out of the sequence), just to be consistent. And you should define those in a config file and then do $this->db->where("status", $this->config->item("status_ALL")); Or something like that. That would be the best practice approach.
#5

[eluser]Nick_MyShuitings[/eluser]
[quote author="Andy UK" date="1304718314"]Thanks!


Code:
$this->db->where("status", 1);
$this->db->or_where("status", 1);

[/quote]

Wait... what??? when the user chooses "one" you are executing this SQL "... WHERE status = 1 OR status = 1" .... WHY???

STOP F-ING using Active Record if your brain can handle SQL! It leads to silly things like this.

[EDIT] Ignore this rant... I see you posted those first options of examples of what would not work due to the post format of your form [/EDIT]




Theme © iAndrew 2016 - Forum software by © MyBB