Need advice on this class function

How safe is this class function. Any improvement please guide me.

public function AddEditCompany($primaryid,$data){
		$updatableFields = array('company_code','company_name','contact_person','company_logo','company_area','company_address','company_contact','company_mobile','company_email','activate');
		
		$isexist = self::isexist($primaryid,$data['company_code']);
		if($isexist == 0){
		 	$ins_sql  = $primaryid==0?"INSERT INTO ".$this->tablename." SET ":"";//insert or update
			$wheresql  =  $primaryid==0?"":" WHERE company_id=" . (int) $primaryid;
			$addsql = "";
			foreach($data as $key=>$val){
				if(in_array($key,$updatableFields)){
					$addsql .= "`" . $key . "`='".dbconnect::escape($val)."'";
				}
			}
			$finalsql  = $ins_sql.$addsql.$wheresql;
			if(dbconnect::query($finalsql)){
				return 1;
			}else{
				return 'Unable to Update. Data Error.';
			};
		} else {
			return 'Company Code Already Exists. Try different one.';
		}
	}

if $primaryid is not 0, you will send an invalid query.

I would suggest you look at INSERT…ON DUPLICATE KEY UPDATE in your database flavor’s documentation. It will simplify your logic significantly.

1 Like

There’s too much going on in that method and would be more difficult than it needs to be to do unit testing on it. Post or PM. the entire class and I will see about showing you a much better way to go about this.

Good catch [m_hutley]. Sorry this idea came out of no where. I just typed and posted. will correct it.

Since I want this function to work on everywhere I am stopping the idea of DUPLICATE KEY UPDATE somewhat difficult for other members.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.