标签归档:Ecshop

Ecshop的MySQL类autoReplace()方法重写

如题:

    // autoReplace
    public function autoReplace($table, $field_values, $update_values, $where = '')
    {
        $field_descs = $this->getAll('DESC ' . $table);

        // primary key | fields
        $primary_keys = $field_names = array();
        foreach ($field_descs as $value) {
            $field_names[] = $value['Field'];
            
            if ($value['Key'] == 'PRI')  {
                $primary_keys[] = $value['Field'];
            }
        }

        // action fields
        $fields = $values = array();
        foreach ($field_names as $value) {
            if (array_key_exists($value, $field_values) ) {
                $fields[] = $value;
                $values[] = "'" . $field_values[$value] . "'";
            }
        }

        // sets
        $sets = array();
        foreach ($update_values as $key => $value) {
            if (array_key_exists($key, $field_values) ) {
                if (is_int($value) || is_float($value)) {
                    $sets[] = $key . ' = ' . $key . ' + ' . $value;
                } else {
                    $sets[] = $key . " = '" . $value . "'";
                }
            }
        }
        
        // not exists primary key
        if (empty($primary_keys) && !empty($fields)) {
        	$sql = 'INSERT INTO ' . $table . '(' . implode(', ', $fields) . ') VALUES(' . implode(', ', $values) . ')';
        } else {
        	if ($this->version() >= 40102) {
        		$sql = 'INSERT INTO '. $table .'('. implode(',', $fields) .') VALUES('. implode(',', $values) .')';
        		
        		if (!empty($sets)) {
        			$sql .= ' ON DUPLICATE KEY UPDATE  '. implode(',', $sets);	
        		}
        	} else {
        		// where
        		if (empty($where)) {
        			$where = array();
        			
        			foreach ($primary_keys as $key) {
        				$where[] = $key = "'". $field_values[$key] ."'" ;
        			}
        			
        			$where = implode(' AND ', $where);
        		}
        		
        		if (!empty($where) && (!empty($sets) || !empty($fields))) {
        			if (intval($GLOBALS['db']->getOne("SELECT COUNT(*) FROM $table WHERE $where")) > 0) {
        				if (!empty($sets)) {
        					$sql = 'UPDATE '. $table .' SET '. implode(',', $sets) .' WHERE '. $where;
        				}
        			} else {
        				if (!empty($fields)) {
        					$sql = 'REPLACE INTO '. $table .'('. implode(',', $fields) .') VALUES('. implode(',', $values) .')';
        				}
        			} // else
        		}
        	} // else
        } // end if
        
        return empty($sql) ? false : $this->query($sql);
    }

已经重写过MySQL类(使用MySQLi方法),需要者Email:ljlwill@gmail.com。