Reputation: 669
Example:
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
}
How can I know if joel, joelle,joe and joela datastatus are all same and not same?
How can I know the output of that example.. the output should be false because all of the status are not same, and In case all of the status are the same how can I know that?
Hope someone could help me thanks in advance..
Upvotes: 0
Views: 756
Reputation: 442
Try this logic
Don't need to implode array
. Just pass array in where_in
like this-
$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";
}
}
Upvotes: 0
Reputation: 4858
Modify your query like below.
$namesStr = "'" . implode("','", $names) . "'";
$qcheck = $this->db->query("SELECT COUNT(DISTINCT datastatus) AS dataCount FROM table_data WHERE dataname IN ($namesStr)");
Your query will look like...
SELECT COUNT(DISTINCT datastatus) AS dataCount FROM table_data WHERE dataname IN ('joel','joelle','joe','joela')
Upvotes: 1
Reputation: 4749
Try this optimized logic:
$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;
}
}
Upvotes: 2
Reputation: 11987
You can try like this,
$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
}
}
Upvotes: 0