MCIT Trends
MCIT Trends

Reputation: 281

Session data in Codeigniter

I have a simple program that manages documents' data. A document has a branch_id & subject_id.
Some documents have:
a) Only the branch_id & subject_id is null.
b) Only the subject_id & branch_id is null.
c) Both the branch_id & subject_id.

I need to separate all the files by the above criteria. In my project, I used the following code to do this

if ($this->session->userdata('branch_id'))
      $this->db->where('tbl_documents.branch_id', $this->session->userdata('branch_id'));
if ($this->session->userdata('subject_id'))
      $this->db->where('tbl_documents.subject_id', $this->session->userdata('subject_id'));

How can I modify above code to fulfill criteria c) mentioned above. Can anyone help me?

Upvotes: 0

Views: 61

Answers (2)

Captain Red
Captain Red

Reputation: 1171

Try the Associative array method

if (($this->session->userdata('branch_id')) && ($this->session->userdata('subject_id')))
{
  $where = array(
                'branch_id' => $this->session->userdata('branch_id'), 
                'subject_id' => $this->session->userdata('subject_id')
                );
 }
else if($this->session->userdata('branch_id'))
{
  $where = array('branch_id' => $this->session->userdata('branch_id'));
}
else if($this->session->userdata('subject_id'))
{
  $where = array('subject_id' => $this->session->userdata('subject_id'));
}
else
{
  $where = array('1' => '1'); //You probably don't need this case.
}

$this->db->where($where);
$this->db->get('tbl_documents');

Upvotes: 1

DFriend
DFriend

Reputation: 8964

I don't believe you need to do anything.

Let's assume you're asking for all fields from tbl_documents so the "base-line" query statement is

SELECT * FROM tbl_documents

That will not change unless one or both of the if statements are true.

If the first is true, then the query statement becomes

SELECT * FROM tbl_documents WHERE tbl_documents.branch_id = some_branch_id;

However, if the first were false and the second true then the statement would be

SELECT * FROM tbl_documents WHERE tbl_documents.subject_id = some_subject_id;

Should both if conditions be true the query statement would be

SELECT * FROM tbl_documents WHERE tbl_documents.branch_id = some_branch_id 
                             AND tbl_documents.subject_id = some_subject_id;

Doesn't that satisfy the criteria "c"?

The question I have is, what if both conditions are false? Is SELECT * FROM tbl_documents (no WHERE conditions) a query you actually want to run?

Upvotes: 0

Related Questions