有一个表包含
之类的列username,settings1,settings2,settings3
用户名是唯一的,而settings1,2,3包含0或1个值。
$query = $this->db->query("SELECT * FROM tbl_users WHERE username = 'test'");
$queryrow = $query->row();
所以我想选择与用户名匹配的行并循环遍历列并检查哪个列包含0和1
我可以通过为每列编写if语句来完成此操作,例如
if($queryrow->settings1=="1"){
..
}
表中有7列,所以不是写7 if语句,还有其他方法吗?即时通讯使用codeigniter 2.0.2
此致
答案 0 :(得分: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
答案 1 :(得分:1)
您可以使用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]);
答案 2 :(得分:0)
您可以迭代对象
// 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
}
}
}
如果您在此循环中需要执行的操作是检查这些值,则应该执行SELECT以仅在$ row中包含这些项目,并避免使用“username”
$this->db->select('setting1, setting2, setting3');
否则,如果你想保留用户名,那么IF语句可能是
if(in_array($key, array('setting1', 'setting2', 'setting3')) && $row->$key == "1")