Sahib Uz Zaman Sahib Uz Zaman - 20 days ago 5
PHP Question

Move to the next element in foreach loop if entry already in the table

I am basically running an upload file for users with their information on my application that is developed on codeigniter. It gets one row from the file and updates the table if the entry doesnt exist.

But I want to first check whether the entry is already in the database or not. In case it is it should move to the next element.

Following is my Model code.

function upload($file_name){
$file = './uploads/'.$file_name;


$this->load->library('excel');

$objPHPExcel = PHPExcel_IOFactory::load($file);

$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();

foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();


if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
//send the data in an array format
$data['header'] = $header;
$data['values'] = $arr_data;
foreach ($arr_data as $q){
$data = array(
't_ref'=>$q['A'],
't_name'=>ucwords($q['B']),
't_cnic'=>$q['C'],
't_dept'=>$q['D'],
'status'=>$q['E']
);
$this->db->select('t_cnic');
$this->db->where('t_cnic',$q['C']);
$this->db->from('tbl_users');
$query = $this->db->get();
if($query->num_rows()>0){
break;
}else{
$this->db->insert('tbl_users',$data);
}
}
$msg = "Successfully Added";
return $msg;
}


(Break is not moving to the next element ofcourse)

How can i move to the next element rather than just stopping the loop whenever it finds an entry with the CNIC already existing in the table.

Answer

You don't need to break, or continue here, just tidy up the logic:

if ($query->num_rows()==0) {
    $this->db->insert('tbl_users',$data);
}