0

There is a table contains columns like

username,settings1,settings2,settings3

username is a unique and settings1,2,3 is contain 0 or 1 values.

$query = $this->db->query("SELECT * FROM tbl_users WHERE username = 'test'");
$queryrow = $query->row();

so i want to select the row that matching to username and loop through columns and check which column contain 0's and 1's

i can do this by writing a if statement for every column though, like

if($queryrow->settings1=="1"){
..
}

there is like 7 columns in table so instead of writing 7 if statements, any other way to do this? im using codeigniter 2.0.2

Regards

Gihan Lasita
  • 2,955
  • 13
  • 48
  • 65

3 Answers3

1
// use active record to work even less and be safer 
$query = $this->db->get_where('tbl_users', array('username' => 'test'));
if($query->num_rows() < 1){
    //prevent errors
    return false; // or do something more apropriate
}

$data = $query->row();
$data->setting1; // contains setting1 value
$data->setting2; // contains setting2 value
$data->setting3; // contains setting3 value
Ivan Ivanic
  • 2,982
  • 1
  • 20
  • 21
  • the thing is i want to check settings value too whether its contain 1 or 0 – Gihan Lasita Aug 21 '11 at 11:24
  • Well than, I do not think there is any other way to do it than to call `if` for every setting. You will somewhere have to write what to do depending of value of each setting, and you can achieve it only with `if` statement. If you wrote what those settings do, than maybe some of them can be compounded, if they are exclusive to each other, but that is db table desing question :) – Ivan Ivanic Aug 21 '11 at 12:00
1

You can outputing an array from table using activerecord

$qry = $this->db->get_where('tbl_users',array('username' => 'test'));
$res = $qry->result_array();

// Since you mention each username is a unique, then this should outputing the array of settings
var_dump($res[0]);
toopay
  • 1,635
  • 11
  • 18
0

You can iterate objects

// use active record to work less and be safer
$this->db->where('username', 'test');
$query = $this->db->get('tbl_users');

foreach ($query->result() as $row)
{
    // iterate the row object
    foreach($row as $key => $item)
    {
        if($row->$key == "1")
        {
            // your code
        }
    }
}

If all you need to do in this loop is checking those values, you should do a SELECT to have only those items in $row, and avoid having "username"

$this->db->select('setting1, setting2, setting3');

Otherwise, if you want to keep username, the IF statement could be rather

if(in_array($key, array('setting1', 'setting2', 'setting3')) && $row->$key == "1")
Woxxy
  • 1,313
  • 10
  • 12