Welcome Guest, Not a member yet? Register   Sign In
How to join 3 columns in a table?
#1

[eluser]gojo[/eluser]
I have a table called holidays and it has among other columns, 3 columns called destination1, destination2 and destination3.
I want to see if a user has been to Spain which could be in any of his 3 destination columns.
So I wrote a query asking the following

Code:
$this->db->select('name, location,destination1, destination2, destination3, id');
$this->db->from('holidays');
$this->db->limit($limit, $offset);
$this->db->order_by($sort_by, $sort_order);
if (strlen($query_array['stayed']))
            {
$where = "destination1='Spain' OR destination2='Spain' OR destination3='Spain'";
$this->db->where($where);
}
  if (strlen($query_array['name'])) {
   $this->db->like('name', $query_array['name']);}
  if (strlen($query_array['location'])) {
   $this->db->like('location', $query_array['location']);
    }
  $ret['rows'] = $this->db->get()->result();
But it keeps returning everyone in spain or just a few when I want say everyone named Steve who have visited spain.... is there a better way to query this please.
Gary
#2

[eluser]TheFuzzy0ne[/eluser]
If you want to use LIKE, your value should contain at least one wildcard (%). However, I don't think you should be using like here. If you want to find peple call "Paul", that who it should find. If you use like, you'll get results for Pauly, Paulie, Paula and so on. Is that what you want?

Also, your going to have problems if you hardcode the destination. The destination should be dynamic, and in a model. Although it may be more confusing for you at first, it gives you an API that you can re-use, and you won't have to keep rewriting the same code.
Code:
$destination = 'Spain';

$this->db->select('name, location,destination1, destination2, destination3, id');
$this->db->from('holidays');

if (isset($query_array['stayed']))
{
    $this->db->where('(`destination1`="Spain" OR `destination2`="Spain" OR `destination3`="Spain")', NULL, FALSE);
}
if (isset($query_array['name']))
{
    $this->db->where('name', $query_array['name']);
}
if (isset($query_array['location']))
{
    $this->db->where('location', $query_array['location']);
}

$this->db->limit($limit, $offset);
$this->db->order_by($sort_by, $sort_order);

$ret['rows'] = $this->db->get()->result();

To be honest, I'm still not sure that's going to get the result you want. When you have to start adding numbers to database field names (destination1, destination2 etc...), that's normally a pretty good indication that your database design is flawed.
#3

[eluser]gojo[/eluser]
Maybe I can join the destinations together, I will search the net to see. Thanks for your help Smile




Theme © iAndrew 2016 - Forum software by © MyBB