示例:
Mysql - table_data
dataid dataname datastatus
1 joel 1
1 joelle 2
1 joe 3
1 joela 4
1 joella 5
PHP
$names = array('joel','joelle','joe','joela');
foreach($names as $name)
{
$qcheck = $this->db->query("SELECT * FROM table_data WHERE dataname=".$name."");
//Do checking here
}
我怎么知道joel,joelle,joe和joela datastatus是否都相同且不相同?
我如何知道该示例的输出..输出应该为false,因为所有状态都不相同,如果所有状态都相同,我怎么知道?
希望有人能提前帮助我...
答案 0 :(得分:2)
尝试这种优化逻辑:
$namesStr = implode(',', $names);
$qcheck = $this->db->query("SELECT COUNT(DISTINCT datastatus) AS dataCount FROM table_data WHERE dataname IN($namesStr)");
$allSame = FALSE;
if ($qcheck->num_rows() > 0) {
if ($qcheck->row()->dataCount == 1) {
$allSame = TRUE;
}
}
答案 1 :(得分:1)
修改您的查询,如下所示。
$namesStr = "'" . implode("','", $names) . "'";
$qcheck = $this->db->query("SELECT COUNT(DISTINCT datastatus) AS dataCount FROM table_data WHERE dataname IN ($namesStr)");
您的查询看起来像......
SELECT COUNT(DISTINCT datastatus) AS dataCount FROM table_data WHERE dataname IN ('joel','joelle','joe','joela')
答案 2 :(得分:0)
你可以这样试试,
$names = array('joel','joelle','joe','joela');
$qcheck = $this->db->query("SELECT datastatus FROM table_data WHERE dataname=".$name."")->result_array;
foreach($names as $name)
{
if(in_array($name,$qcheck)){
//name exists
} else {
//name doesnot exists
}
}
答案 3 :(得分:0)
试试这个逻辑
不需要implode array
。只需在where_in
中传递数组,就像这样 -
$names = array('joel','joelle','joe','joela');
$this->db->select("COUNT(DISTINCT datastatus) AS dataCount");
$this->db->from("table_data");
$this->db->where_in('dataname',$names);
$q=$this->db->get();
if($q->num_rows() > 0){
$result=$q->row();
if ($result->dataCount == 1) {
echo "true";
}
}