In SugarCRM (program management) module called "projects" by default does not come with the "import", it added eh following programming steps:
http://forums.sugarcrm.com/f148/how-add-importación-opción-custom-modules-45612/
Now I throw the error when I Import Next:
Fatal error: Llamada a una función miembro get_importable_fields () en un no-objeto en C: \ Archivos de programa \ Apache Software Foundation \ Apache2.2 \ htdocs \ Azúcar \ modules \ Import \ v iews \ view.step3.php en línea 217
Please somebody help me ... if necessary ... I will upload the file so they can help view.step3.php
Here is the line 217:
$fields = $this->bean->get_importable_fields();
$options = array();
$defaultField = '';
global $current_language;
$moduleStrings = return_module_language($current_language, $this->bean->module_dir);
Here I publish the above lines:
class ImportViewStep3 extends ImportView
{
protected $pageTitleKey = 'LBL_STEP_3_TITLE';
protected $currentFormID = 'importstep3';
protected $previousAction = 'Confirm';
protected $nextAction = 'dupcheck';
/**
* #see SugarView::display()
*/
public function display()
{
global $mod_strings, $app_strings, $current_user, $sugar_config, $app_list_strings, $locale;
$this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
$has_header = ( isset( $_REQUEST['has_header']) ? 1 : 0 );
$sugar_config['import_max_records_per_file'] = ( empty($sugar_config['import_max_records_per_file']) ? 1000 : $sugar_config['import_max_records_per_file'] );
$this->ss->assign("CURRENT_STEP", $this->currentStep);
// attempt to lookup a preexisting field map
// use the custom one if specfied to do so in step 1
$mapping_file = new ImportMap();
$field_map = $mapping_file->set_get_import_wizard_fields();
$default_values = array();
$ignored_fields = array();
if ( !empty( $_REQUEST['source_id']))
{
$GLOBALS['log']->fatal("Loading import map properties.");
$mapping_file = new ImportMap();
$mapping_file->retrieve( $_REQUEST['source_id'],false);
$_REQUEST['source'] = $mapping_file->source;
$has_header = $mapping_file->has_header;
if (isset($mapping_file->delimiter))
$_REQUEST['custom_delimiter'] = $mapping_file->delimiter;
if (isset($mapping_file->enclosure))
$_REQUEST['custom_enclosure'] = htmlentities($mapping_file->enclosure);
$field_map = $mapping_file->getMapping();
//print_r($field_map);die();
$default_values = $mapping_file->getDefaultValues();
$this->ss->assign("MAPNAME",$mapping_file->name);
$this->ss->assign("CHECKMAP",'checked="checked" value="on"');
}
else
{
$classname = $this->getMappingClassName(ucfirst($_REQUEST['source']));
//Set the $_REQUEST['source'] to be 'other' for ImportMapOther special case
if($classname == 'ImportMapOther')
{
$_REQUEST['source'] = 'other';
}
if (class_exists($classname))
{
$mapping_file = new $classname;
$ignored_fields = $mapping_file->getIgnoredFields($_REQUEST['import_module']);
$field_map2 = $mapping_file->getMapping($_REQUEST['import_module']);
$field_map = array_merge($field_map,$field_map2);
}
}
$delimiter = $this->getRequestDelimiter();
$this->ss->assign("CUSTOM_DELIMITER", $delimiter);
$this->ss->assign("CUSTOM_ENCLOSURE", ( !empty($_REQUEST['custom_enclosure']) ? $_REQUEST['custom_enclosure'] : "" ));
//populate import locale values from import mapping if available, these values will be used througout the rest of the code path
$uploadFileName = $_REQUEST['file_name'];
// Now parse the file and look for errors
$importFile = new ImportFile( $uploadFileName, $delimiter, html_entity_decode($_REQUEST['custom_enclosure'],ENT_QUOTES), FALSE);
if ( !$importFile->fileExists() ) {
$this->_showImportError($mod_strings['LBL_CANNOT_OPEN'],$_REQUEST['import_module'],'Step2');
return;
}
$charset = $importFile->autoDetectCharacterSet();
// retrieve first 3 rows
$rows = array();
//Keep track of the largest row count found.
$maxFieldCount = 0;
for ( $i = 0; $i < 3; $i++ )
{
$rows[] = $importFile->getNextRow();
$maxFieldCount = $importFile->getFieldCount() > $maxFieldCount ? $importFile->getFieldCount() : $maxFieldCount;
}
$ret_field_count = $maxFieldCount;
// Bug 14689 - Parse the first data row to make sure it has non-empty data in it
$isempty = true;
if ( $rows[(int)$has_header] != false ) {
foreach ( $rows[(int)$has_header] as $value ) {
if ( strlen(trim($value)) > 0 ) {
$isempty = false;
break;
}
}
}
if ($isempty || $rows[(int)$has_header] == false) {
$this->_showImportError($mod_strings['LBL_NO_LINES'],$_REQUEST['import_module'],'Step2');
return;
}
// save first row to send to step 4
$this->ss->assign("FIRSTROW", base64_encode(serialize($rows[0])));
// Now build template
$this->ss->assign("TMP_FILE", $uploadFileName );
$this->ss->assign("SOURCE", $_REQUEST['source'] );
$this->ss->assign("TYPE", $_REQUEST['type'] );
$this->ss->assign("DELETE_INLINE_PNG", SugarThemeRegistry::current()->getImage('basic_search','align="absmiddle" alt="'.$app_strings['LNK_DELETE'].'" border="0"'));
$this->ss->assign("PUBLISH_INLINE_PNG", SugarThemeRegistry::current()->getImage('advanced_search','align="absmiddle" alt="'.$mod_strings['LBL_PUBLISH'].'" border="0"'));
$this->instruction = 'LBL_SELECT_MAPPING_INSTRUCTION';
$this->ss->assign('INSTRUCTION', $this->getInstruction());
$this->ss->assign("MODULE_TITLE", $this->getModuleTitle(false));
$this->ss->assign("STEP4_TITLE",
strip_tags(str_replace("\n","",getClassicModuleTitle(
$mod_strings['LBL_MODULE_NAME'],
array($mod_strings['LBL_MODULE_NAME'],$mod_strings['LBL_STEP_4_TITLE']),
false
)))
);
$this->ss->assign("HEADER", $app_strings['LBL_IMPORT']." ". $mod_strings['LBL_MODULE_NAME']);
// we export it as email_address, but import as email1
$field_map['email_address'] = 'email1';
// build each row; row count is determined by the the number of fields in the import file
$columns = array();
$mappedFields = array();
// this should be populated if the request comes from a 'Back' button click
$importColumns = $this->getImportColumns();
$column_sel_from_req = false;
if (!empty($importColumns)) {
$column_sel_from_req = true;
}
for($field_count = 0; $field_count < $ret_field_count; $field_count++) {
// See if we have any field map matches
$defaultValue = "";
// Bug 31260 - If the data rows have more columns than the header row, then just add a new header column
if ( !isset($rows[0][$field_count]) )
$rows[0][$field_count] = '';
// See if we can match the import row to a field in the list of fields to import
$firstrow_name = trim(str_replace(":","",$rows[0][$field_count]));
if ($has_header && isset( $field_map[$firstrow_name] ) ) {
$defaultValue = $field_map[$firstrow_name];
}
elseif (isset($field_map[$field_count])) {
$defaultValue = $field_map[$field_count];
}
elseif (empty( $_REQUEST['source_id'])) {
$defaultValue = trim($rows[0][$field_count]);
}
// build string of options
$fields = $this->bean->get_importable_fields();
this is my coding project.php:
class Project extends SugarBean {
// database table columns
var $id;
var $date_entered;
var $date_modified;
var $assigned_user_id;
var $modified_user_id;
var $created_by;
var $name;
var $description;
var $deleted;
// related information
var $assigned_user_name;
var $modified_by_name;
var $created_by_name;
var $account_id;
var $contact_id;
var $opportunity_id;
var $email_id;
var $estimated_start_date;
// calculated information
var $total_estimated_effort;
var $total_actual_effort;
var $object_name = 'Project';
var $module_dir = 'Project';
var $new_schema = true;
var $table_name = 'project';
var $importable = true;
// This is used to retrieve related fields from form posts.
var $additional_column_fields = array(
'account_id',
'contact_id',
'opportunity_id',
);
var $relationship_fields = array(
'account_id' => 'accounts',
'contact_id'=>'contacts',
'opportunity_id'=>'opportunities',
'email_id' => 'emails',
);
//////////////////////////////////////////////////////////////////
// METHODS
//////////////////////////////////////////////////////////////////
/**
*
*/
function Project()
{
parent::SugarBean();
}
/**
* overriding the base class function to do a join with users table
*/
/**
*
*/
function fill_in_additional_detail_fields()
{
parent::fill_in_additional_detail_fields();
$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
//$this->total_estimated_effort = $this->_get_total_estimated_effort($this->id);
//$this->total_actual_effort = $this->_get_total_actual_effort($this->id);
}
/**
*
*/
function fill_in_additional_list_fields()
{
parent::fill_in_additional_list_fields();
$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
//$this->total_estimated_effort = $this->_get_total_estimated_effort($this->id);
//$this->total_actual_effort = $this->_get_total_actual_effort($this->id);
}
/**
* Save changes that have been made to a relationship.
*
* #param $is_update true if this save is an update.
*/
function save_relationship_changes($is_update, $exclude=array())
{
parent::save_relationship_changes($is_update, $exclude);
$new_rel_id = false;
$new_rel_link = false;
//this allows us to dynamically relate modules without adding it to the relationship_fields array
if(!empty($_REQUEST['relate_id']) && !in_array($_REQUEST['relate_to'], $exclude) && $_REQUEST['relate_id'] != $this->id){
$new_rel_id = $_REQUEST['relate_id'];
$new_rel_relname = $_REQUEST['relate_to'];
if(!empty($this->in_workflow) && !empty($this->not_use_rel_in_req)) {
$new_rel_id = $this->new_rel_id;
$new_rel_relname = $this->new_rel_relname;
}
$new_rel_link = $new_rel_relname;
//Try to find the link in this bean based on the relationship
foreach ( $this->field_defs as $key => $def ) {
if (isset($def['type']) && $def['type'] == 'link'
&& isset($def['relationship']) && $def['relationship'] == $new_rel_relname) {
$new_rel_link = $key;
}
}
if ($new_rel_link == 'contacts') {
$accountId = $this->db->getOne('SELECT account_id FROM accounts_contacts WHERE contact_id=' . $this->db->quoted($new_rel_id));
if ($accountId !== false) {
if($this->load_relationship('accounts')){
$this->accounts->add($accountId);
}
}
}
}
}
/**
*
*/
function _get_total_estimated_effort($project_id)
{
$return_value = '';
$query = 'SELECT SUM('.$this->db->convert('estimated_effort', "IFNULL", 0).') total_estimated_effort';
$query.= ' FROM project_task';
$query.= " WHERE parent_id='{$project_id}' AND deleted=0";
$result = $this->db->query($query,true," Error filling in additional detail fields: ");
$row = $this->db->fetchByAssoc($result);
if($row != null)
{
$return_value = $row['total_estimated_effort'];
}
return $return_value;
}
/**
*
*/
function _get_total_actual_effort($project_id)
{
$return_value = '';
$query = 'SELECT SUM('.$this->db->convert('actual_effort', "IFNULL", 0).') total_actual_effort';
$query.= ' FROM project_task';
$query.= " WHERE parent_id='{$project_id}' AND deleted=0";
$result = $this->db->query($query,true," Error filling in additional detail fields: ");
$row = $this->db->fetchByAssoc($result);
if($row != null)
{
$return_value = $row['total_actual_effort'];
}
return $return_value;
}
/**
*
*/
function get_summary_text()
{
return $this->name;
}
/**
*
*/
function build_generic_where_clause ($the_query_string)
{
$where_clauses = array();
$the_query_string = $GLOBALS['db']->quote($the_query_string);
array_push($where_clauses, "project.name LIKE '%$the_query_string%'");
$the_where = '';
foreach($where_clauses as $clause)
{
if($the_where != '') $the_where .= " OR ";
$the_where .= $clause;
}
return $the_where;
}
function get_list_view_data()
{
$field_list = $this->get_list_view_array();
$field_list['USER_NAME'] = empty($this->user_name) ? '' : $this->user_name;
$field_list['ASSIGNED_USER_NAME'] = $this->assigned_user_name;
return $field_list;
}
function bean_implements($interface){
switch($interface){
case 'ACL':return true;
}
return false;
}
function create_export_query(&$order_by, &$where, $relate_link_join='')
{
$custom_join = $this->custom_fields->getJOIN(true, true,$where);
if($custom_join)
$custom_join['join'] .= $relate_link_join;
$query = "SELECT
project.*,
users.user_name as assigned_user_name ";
if($custom_join){
$query .= $custom_join['select'];
}
$query .= " FROM project ";
if($custom_join){
$query .= $custom_join['join'];
}
$query .= " LEFT JOIN users
ON project.assigned_user_id=users.id ";
$where_auto = " project.deleted=0 ";
if($where != "")
$query .= "where ($where) AND ".$where_auto;
else
$query .= "where ".$where_auto;
if(!empty($order_by)){
//check to see if order by variable already has table name by looking for dot "."
$table_defined_already = strpos($order_by, ".");
if($table_defined_already === false){
//table not defined yet, define accounts to avoid "ambigous column" SQL error
$query .= " ORDER BY $order_by";
}else{
//table already defined, just add it to end of query
$query .= " ORDER BY $order_by";
}
}
return $query;
}
function getAllProjectTasks(){
$projectTasks = array();
$query = "SELECT * FROM project_task WHERE project_id = '" . $this->id. "' AND deleted = 0 ORDER BY project_task_id";
$result = $this->db->query($query,true,"Error retrieving project tasks");
$row = $this->db->fetchByAssoc($result);
while ($row != null){
$projectTaskBean = new ProjectTask();
$projectTaskBean->id = $row['id'];
$projectTaskBean->retrieve();
array_push($projectTasks, $projectTaskBean);
$row = $this->db->fetchByAssoc($result);
}
return $projectTasks;
}
}
?>
Related
Please help me about this one.
i have a table name 'aptimportdata' and 'aptimportdataaddress'.
the code below is a function for import a microsoft excel data to the website.
i want to send a data from table aptimportdata to aptimportdataaddress, but i don't know how, because in the excel file, there are 2 home address columns for one person, one with the columns name homeaddress1 to 4, and the other one is altaddress1 to 4, the "altaddress" is created for a person who have a home address more than 1.
now when i import the data from the website, the data is sent to the aptimportdata table and it doesn't have a problem when i upload the file from the website, but when i change the "altaddress" data destination table to aptimportdataaddress table, the website just give me an endless loading without a success report.
i already make a column for the "altaddress" in aptimportdataaddress table, but i cant find a solution how to make the "altaddress" data go to aptimportaddress table and its just the "altaddress" column data that i want to put at the aptimportdataaddress table.
if you need a screenshot for the what the table looks like, i'll send it.
this is my code :
= 5.3.3
* #copyright 2014 Sereware
* #developer Yudha Tama Aditiyara
* #application controller/apartement
*/
class import extends Controller
{
protected $_models = array('apartement/import/m_import');
public function dataexcel(){
$config['ajax_upload_dataexcel'] = site_url('apartement/import/ajax_upload_dataexcel');
$config['ajax_process_dataexcel'] = site_url('apartement/import/ajax_process_dataexcel/'.$this->d_page->page('noid'));
$this->load->view('apartement/import/dataexcel',$config);
}
public function ajax_upload_dataexcel(){
$id = str_replace('.','',microtime(true));
$upload = new Sereware\ExcelUpload(array('upload_dir' => SYSPATH.'files/'),false);
$upload->hasNormalFilename = true;
$this->d_page->obstart();
$upload->post();
ob_flush();
}
protected $apttower = array(
'h' => 1,'s'=>2,'y'=>3,'p'=>4
);
#{{{
protected function get_dataexcel(){
if (!isset($_REQUEST['file']) || !trim($_REQUEST['file']))return;
$file = $_REQUEST['file'];
$file = SYSPATH."files/" . $file . (pathinfo($file,PATHINFO_EXTENSION) !== 'xls' ? '.xls' : '');
if (!file_exists($file)) return;
$excel = new Sereware\Excel($file);
$data = $excel->getCells(0);
return $data;
}
protected function matcher_excelfield($dataexcelfields, $appimportdetails){
$fieldnames = array();
foreach($dataexcelfields as $indexField => $dataexcelfield) {
$dataexcelfield = strtolower(preg_replace('#[\n\r]#','',trim($dataexcelfield)));
if (isset($appimportdetails[$dataexcelfield])) {
$destfield = preg_replace('#[\n\r]#','',$appimportdetails[$dataexcelfield]->destfield);
$desttypefield = (int)$appimportdetails[$dataexcelfield]->desttypefield;
$isnormalized = $appimportdetails[$dataexcelfield]->isnormalized;
$defaultvalue = $appimportdetails[$dataexcelfield]->defaultvalue;
$appimportdetail = $appimportdetails[$dataexcelfield];
$appimportdetail_desttables = array_filter(explode(';',$appimportdetail->desttable));
foreach($appimportdetail_desttables as $tablename) {
$fieldnames[$tablename][$indexField] = array(
'destfield' => $destfield,
'desttypefield' => $desttypefield,
'isnormalized' => $isnormalized,
'defaultvalue' => $defaultvalue
);
}
}
}
return $fieldnames;
}
protected function normalize_dataexcel($destfield,$value){
$value = trim($value);
switch($destfield) {
case 25:
$value = str_replace('%','',$value);
break;
case 11:
if ($value){
$value = strtotime(str_replace('/', '-',(string)$value));
$value = date('Y-m-d',$value);
} else {
$value = null;
}
break;
case 34:
if (!$value) {
$value = -1;
} else {
$value = strtolower($value) === 'ok' ? 1 : 0;
}
break;
}
return $value;
}
public function ajax_process_dataexcel($idpage){
$appimport = $this->m_import->get_appimport();
$appimportdetails = $this->m_import->get_appimportdetails($appimport->idconnection,$appimport->noid);
$aptimportdatas = $this->m_import->get_aptimportdatas($appimport->idconnection);
$newid_aptimportdata = $this->m_import->get_maxid_aptimportdata();
$aptsyarats = $this->m_import->data_aptsyarats();
$aptdatabap = $this->m_import->data_aptbap();
$dataexcel = $this->get_dataexcel();
$dataexcelfields = $this->matcher_excelfield(array_shift($dataexcel),$appimportdetails);
$insert_data = array();
$update_data = array();
$insert_data_aptunitroom = array();
$insert_data_aptimportdataaddress = array();
$insert_data_aptunitroomsyarat = array();
$insert_data_aptdatabap = array();
$datamcarduser = $this->d_page->d_login->get_datamcarduser();
// var_dump(json_encode($dataexcelfields));
// exit();
foreach($dataexcel as $data) {
foreach($dataexcelfields as $tablename => $fieldnames) {
##-1
##-build data per-row
$ndata = array();
$ready = true;
$ndata['idcreate'] = $datamcarduser->noid;
$ndata['idupdate'] = $datamcarduser->noid;
$ndata['docreate'] = date('Y-m-d H:i:s');
$ndata['lastupdate'] = date('Y-m-d H:i:s');
foreach($fieldnames as $indexFieldExcel => $datafields) {
$fieldname = $datafields['destfield'];
$isnormalized = intval($datafields['isnormalized']);
$defaultvalue = $datafields['defaultvalue'];
$desttypefield = $datafields['desttypefield'];
if (!$isnormalized) {
$defaultvalue = $data[$indexFieldExcel];
}
$ndata[$fieldname] = $this->normalize_dataexcel($desttypefield,$defaultvalue);
}
##-2
if (isset($ndata['lotno']) && isset($aptimportdatas[$ndata['lotno']])) {
$metadata = $aptimportdatas[$ndata['lotno']];
if ($tablename === 'aptimportdata') {
$update_data[$tablename][$metadata['metadata']->noid] = $ndata;
// if (!empty($ndata['ppjbdate'])) {
// }
$update_data['aptunitroom'][$metadata['metadata']->noid] = array(
'statuslegal' => empty($ndata['ppjbdate']) ? 0 : 1,
'statusproject' => $ndata['isreadytoho']
);
$mimportlog_r = array_merge(array("noid" => $metadata['metadata']->noid), $ndata);
$insert_data['mimportlog'][] = $mimportlog_r;
continue;
}
$matchers = $metadata['matchers'];
$extrafields = $metadata['extrafields'];
if (isset($matchers[$tablename])) {
foreach($matchers[$tablename] as $_fieldname => $value) {
if ($value === (int)$ndata[$_fieldname]) {
$ready = false;
break;
}
}
}
##-
if ($ready) {
if (isset($extrafields[$tablename])) {
foreach($extrafields[$tablename] as $__fieldname => $_value) {
$ndata[$__fieldname] = $_value;
}
}
}
}
##-3
if ($ready) {
$lotno = false;
if ($tablename === 'aptimportdata') {
$lotno = $ndata['lotno'];
$ndata['noid'] = $newid_aptimportdata;
$insert_data_aptunitroom[] = array(
'noid' => $newid_aptimportdata,
'statusproject' => $ndata['isreadytoho'],
'statuslegal' => empty($ndata['ppjbdate']) ? -1 : 1
);
$insert_data_aptimportdataaddress[] = array(
'noid' => $newid_aptimportdata
);
foreach($aptsyarats as $key => &$aptsyaratdata) {
$aptsyaratdata = (array)$aptsyaratdata;
$aptsyaratdata['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptunitroomsyarat[] = $aptsyaratdata;
}
foreach($aptdatabap as $key => $data){
$data = (array)$data;
$data['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptdatabap[] = $data;
}
$newid_aptimportdata++;
}
if ($lotno !== false) {
$insert_data[$tablename][$lotno] = $ndata;
} else {
$insert_data[$tablename][] = $ndata;
}
}
}
}
$real_insert_data = array();
if (isset($insert_data['aptimportdata'])) {
$_aptimportdata = $insert_data['aptimportdata'];
$real_insert_data['aptimportdata'] = array_values($_aptimportdata);
$real_insert_data['mimportlog'] = array_values($_aptimportdata);
foreach($insert_data as $tablename => $datas) {
if ($tablename !== 'aptimportdata' && $tablename !== 'aptunitroom') {
$real_insert_data[$tablename] = array();
foreach($datas as $key => $data) {
if ((!isset($data['idaptunitroom']) || intval($data['idaptunitroom']) === 0) || $_aptimportdata[$data['lotno']]) {
$data['idaptunitroom'] = $_aptimportdata[$data['lotno']]['noid'];
}
$real_insert_data[$tablename][$key] = $data;
}
}
}
} else {
$real_insert_data = $insert_data;
}
if (!empty($insert_data_aptunitroom)) {
$real_insert_data['aptunitroom'] = $insert_data_aptunitroom;
$real_insert_data['aptimportdataaddress'] = $insert_data_aptimportdataaddress;
}
if (!empty($insert_data_aptunitroomsyarat)) {
$real_insert_data['aptunitroomsyarat'] = $insert_data_aptunitroomsyarat;
$real_insert_data['aptunitroomdatabap'] = $insert_data_aptdatabap;
}
$gagal = array();
$dbase = new Sereware\Query($appimport->idconnection);
// var_dump(json_encode($real_insert_data));
// exit();
if (!empty($real_insert_data)) {
foreach($real_insert_data as $tablename => $data) {
try {
$db = $dbase->table($tablename);
$db->insert($data);
}catch(Exception $e){
$gagal['insert'][$tablename] = $e->getMessage();
}
}
}
if (!empty($update_data)) {
foreach($update_data as $tablename => $datas) {
foreach($datas as $noid => $data) {
try {
$db = $dbase->table($tablename);
$db->where('noid','=',$noid);
$db->update($data);
}catch(Exception $e){
$gagal['update'][$tablename] = $e->getMessage();
}
}
}
}
ob_start();
echo !count($gagal);
ob_flush();
}
#}}}
}
i'm still using localhost, and sublime text.
the "altaddress" and "homeaddress" are not inside the code, because it's a columns in the table. you can only find a table name on the code.
my question is how can i make the "altaddress" data from aptimportdata table go to aptimportdataaddress table, i dont't want the altaddress go to aptimportdata table, i just want the data get to aptimportdataaddress.
Sorry for my bad english, but I really need to know why this plugin does not work at all.
So i have Joomla 3.5.1 + JoomShopping 4.14.1
I want to connect the attributes filter plugin. But it does not work.
Help me please!!!
<?php
// No direct access.
defined('_JEXEC') or die;
class plgJShoppingOxboxAttribsFilter extends JPlugin
{
public function __construct(&$subject, $config)
{
parent::__construct($subject, $config);
}
public function onBeforeQueryCountProductList($controller, &$adv_result, &$adv_from, &$adv_query, &$order_query, &$filters = array())
{
$this->onBeforeQueryGetProductList($controller, &$adv_result, &$adv_from, &$adv_query, &$order_query, &$filters);
}
public function onBeforeQueryGetProductList($controller, &$adv_result, &$adv_from, &$adv_query, &$order_query, &$filters = array())
{
// Ïîëó÷àåì îáúåêò áàçû äàííûõ
$db = JFactory::getDBO();
//
$query = $db->getQuery(true);
//
$query->select('params');
//
$query->from('#__modules');
//
$query->where('module = "mod_oxbox_jshopping_attribute_filter"');
//
$query->where('published = 1');
//
$db->setQuery($query);
//
$list = $db->loadObjectList();
//
if (is_array($list) && count($list))
{
//
foreach ($list as $item)
{
//
$registry = new JRegistry();
//
$registry->loadString($item->params);
//
$item->params = $registry->toArray();
// Ïîëó÷àåì çíà÷åíèå
$vals = JRequest::getVar($item->params->get('param_name'), '');
//
$vals = urldecode($vals);
// Åñëè çíà÷åíèå íå ïóñòîå
if (!empty($vals))
{
// Åñëè ñîäåðæèò òî÷êó ñ çàïÿòîé
if (JString::strpos($vals, ';'))
{
// Ïðåîáðàçóåì â ìàññèâ
$vals = explode(';', $vals);
}
// Åñëè â ìàññèâå òîëüêî îäèí ýëåìåíò
if (is_array($vals) && count($vals) == 1)
{
//
$vals = $vals[1];
}
//
$attr_id = $item->params->get('attr_id');
//
$db->setQuery('SELECT independent FROM #__jshopping_attr WHERE attr_id = '.$attr_id);
// Ïîëó÷àåì ðåçóëüòàò
$independent = $db->loadResult();
// Åñëè àòðèáóò íåçàâèñèìûé
if ($independent)
{
$table = '#__jshopping_products_attr2';
$attr_value_id_field = 'attr_value_id';
}
else
{
$table = '#__jshopping_products_attr';
$attr_value_id_field = 'attr_'.$attr_id;
}
// Åñëè ôèëüòðóåì ïî çíà÷åíèÿì àòðèáóòîâ
if ($item->params->get('param_type', 'value') == 'value')
{
// Åñëè ýòî ìàññèâ
if (is_array($vals))
{
$adv_query .= 'AND prod.product_id IN (SELECT product_id FROM `'.$table.'` AS attr LEFT JOIN #__jshopping_attr_values AS attr_values ON attr_values.value_id = attr.'.$attr_value_id_field.' WHERE `name_ru-RU` in ('.implode(',', $vals).'))';
}
else
{
$adv_query .= 'AND prod.product_id IN (SELECT product_id FROM `'.$table.'` AS attr LEFT JOIN #__jshopping_attr_values AS attr_values ON attr_values.value_id = attr.'.$attr_value_id_field.' WHERE `name_ru-RU`="'.$vals.'")';
}
}
else // èíà÷å ôèëüòðóåì ïî èäåíòèôèêàòîðàì çíà÷åíèé àòðèáóòîâ
{
// Åñëè ýòî ìàññèâ
if (is_array($vals))
{
$adv_query .= ' AND prod.product_id IN (SELECT product_id FROM `'.$table.'` AS attr WHERE attr.'.$attr_value_id_field.' in ('.implode(',', $vals).'))';
}
else
{
$adv_query .= ' AND prod.product_id IN (SELECT attr.product_id FROM `'.$table.'` AS attr WHERE attr.'.$attr_value_id_field.' = '.$vals.')';
}
}
}
}
}
}
}
I am trying to figure out best practices for writing robust object oriented database models in PHP. I would like to use a data access layer and then have an abstract model class that my actual models would be able to extend. I was hoping to be able to encapsulate all basic CRUD functionality in these layers so I don't have to write lots of redundant code. I am having trouble finding tutorial on how to do this. Does anyone know of a tutorial or have example code on how to do this?
If you want to abstract this further to just make procedural calls to DbMgr.php above,
you can use the below code. This will help you develop project fast and anyone who doesn't have database knowledge can also use below methods to develop php mysql application.
CALL THIS FILE : DbMgrInterface.php
//Includes complete implementation of DB operations
require_once __DIR__.'/DbMgr.php';
$perform_Database_Operation = null; // Global variable to reuse the connection
$error_code = null; // Global variable holding the error_code for a transaction
function getDBConfig($config = ''){
$source = 'Func';
$type = 'mysql';
if(isset($config['source'])){
$source = $config['source'];
}
if( (strcasecmp("Func",$source) == 0) && (function_exists('get_DbConfig')) ) {
$config = get_DbConfig();
}
if(isset($config['type'])){
$type = $config['type'];
}
$config['dbType'] = strtolower($type);
$config['servername'] = $config['host'];
$config['Port'] = $config['port'];
$config['userName'] = $config['username'];
$config['passWord'] = $config['password'];
$config['DatabaseName'] = $config['database'];
return $config;
}
/**
Logic: If config array is passed to this method then definitely the new handle is required.
Else, If DBMgrHandle already exists then return the existing handle.
Else, get the default DB config, and instantiate a new DBMgr Handle.
*/
function DBMgr_Handle($config = '') {
global $perform_Database_Operation;
$className = 'DBMgr';
if(is_array($config)){
$config = getDBConfig($config);
if(strcasecmp($config['dbType'], 'mssql') == 0){
$className = 'SSRV';
}
$perform_Database_Operation = new $className($config);
return $perform_Database_Operation;
}
if(isset($perform_Database_Operation))
return $perform_Database_Operation;
$config = getDBConfig($config);
if(strcasecmp($config['dbType'], 'mssql') == 0){
$className = 'SSRV';
}
if(function_exists('getclassObject'))
$perform_Database_Operation = getclassObject($className, $config);
else
$perform_Database_Operation = new $className($config);
return $perform_Database_Operation;
}
/*=====================================================READ==============================================================*/
/*
* #access public
* #param associative_Array $readInput. Format is described below:
* array(
* 'Fields'=> 'Field1, Field2, Field3', //Mandatory
* 'Table'=> 'TableName', //Mandatory
* 'clause'=> 'FieldName = FieldValue', //optional
* 'order' => 'FieldName DESC' //optional
* )
clause refers exact/valid values as mysql query accepts.
clause is a condition to filter output. e.g. 'FieldName = DesiredValue' would return entries where FieldName has DesiredValue value only.
Order refers exact/valid values as mysql query accepts and is used to sort data selection. example value can be 'FieldName ASC' or 'FieldName DESC'.
* #param string $outputFormat. Values can be one of 'RESULT, NUM_ROWS, NUM_ARR, ASSOC', where ASSOC is default value.
* It defines whether the read should return 'mysql result resource/ Numbers of rows in result set / Numbered array / Associative array
* #param string $DataType. Value can only be 'JSON' else ''. Use this to get data set returned as json.
* #param string $keyField_Output. This can be a field name so that indexes of assoc array can be defined with value of the field passed.
*
* #return false, else 0(zero- for no corresponding entry), else output in described format.
* If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Read($readInput, $outputFormat = "ASSOC", $DataType = "", $keyField_Output = '') {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Read($readInput, $outputFormat, $DataType, $keyField_Output);
}
/*=====================================================INSERT==============================================================*/
/*
* #access public
* #param associative_Array $insertInput. Format is described below:
* array(
* 'Table'=> 'TableName', //Mandatory
* 'Fields'=> array( //Mandatory
'FieldName1' =>Value1,
'FieldName2' =>Value2,
'FieldName_n'=>Value_n
)
* )
* So in above associative array the element refered by key 'Fields' is itself an associative array which would specify DbField and corresponding Value to be stored
* #return Inserted Id on success, else false on failure. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Insert($insertInput) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Insert($insertInput);
}
/*=====================================================UPDATE==============================================================*/
/*
* #access public
* #param associative_Array $updateInput. Format is described below:
* array(
* 'Table'=> 'TableName', //Mandatory
* 'Fields'=> array( //Mandatory
'FieldName1' =>Value1,
'FieldName2' =>Value2,
'FieldName_n'=>Value_n
),
* 'clause'=> 'FieldName = FieldValue', //optional
* )
* So in above associative array the element refered by key 'Fields' is itself an associative array which would specify DbField and corresponding Value to be stored
* #return true on success, else false. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Update($updateInput) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Update($updateInput);
}
/*=====================================================DELETE==============================================================*/
/*
* #access public
* #param associative_Array $deleteInput. Format is described below:
* array(
* 'Table'=> 'TableName', //Mandatory
* 'clause'=> 'FieldName = FieldValue', //OPTIONAL. But if not specified all the data from database would be deleted
* )
* So in above associative array the element refered by key 'Fields' is itself an associative array which would specify DbField and corresponding Value to be stored
* #return true on success, else false on failure. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Delete($deleteInput) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Delete($deleteInput);
}
/*=====================================================RUN ABSOLUTE QUERY==============================================================*/
/*
* #access public
* #param Query as a string. Query can be of any type
* #param string $outputFormat. Values can be one of 'RESULT, NUM_ROWS, NUM_ARR, ASSOC', where ASSOC is default value.
* It defines whether the read should return 'mysql result resource/ Numbers of rows in result set / Numbered array / Associative array
* #param string $DataType. Value can only be 'JSON' else ''. Use this to get data set returned as json.
* #param string $keyField_Output. This can be a field name so that indexes of assoc array can be defined with value of the field passed.
*
* #return false, else 0(zero- for no corresponding entry), else output in described format. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Query($query, $outputFormat = "ASSOC", $DataType = "", $keyField_Output = '') {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Query($query, $outputFormat, $DataType, $keyField_Output);
}
/**
* The function makes a complete database dump of dump for selective tables, depending upon the TABLE_LIST. If TABLE_LIST is empty,
* a complete database dump is made, else dump for selective tables is carried out.
* #param unknown $ExportDBArray
* $ExportDBArray = array(
'DUMP_FILE_NAME' => 'dump.sql', // optional
'TABLE_LIST' => array( // optional
'Table1' => 'userinfo',
'Table2' => 'usageinfo'
)
);
* #return boolean
*/
function DB_ExportTable($ExportDBArray) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Export($ExportDBArray);
}
/**
* The function imports SQL Dump from the given file path.
* #param unknown $ImportDBArray
* $ImportDBArray = array(
'COMPLETE_PATH' => __DIR__ . "\\database_dump.sql"
);
*/
function DB_ImportTable($ImportDBArray) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Import($ImportDBArray);
}
/**
*
* #param unknown $multipleFieldsArray
* $multipleFieldsArray = array(
'TABLE_NAME' => 'userinfo',
'ID_LIST' => true ,
'FIELD_DETAILS' => array(
array('Username' => 'bjam123','Password' =>md5('password123'), 'UserType' => 1),
array('Username' => 'ppu12', 'Password' => md5('password1234'), 'UserType' => 2),
array('Username' => 'ppu13', 'Password' => md5('password12345'), 'UserType' => 3),
array('Username' => 'ppu14', 'Password' => md5('password123456'), 'UserType' => 4)
)
);
* #return array containing the insert_id
*/
function DB_InsertMultipleRows($multipleFieldsArray) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->InsertMR($multipleFieldsArray);
}
/**
* Call this function to perform MSSQL Server specific transactions
* #param unknown $fieldValueArray
* Format is described below:
* array(
* 'Fields'=> 'Field1, Field2, Field3', //Mandatory
* 'Table'=> 'TableName', //Mandatory
* 'clause'=> 'FieldName = FieldValue', //optional
* 'order' => 'FieldName DESC' //optional
* )
clause refers exact/valid values as mysql query accepts.
clause is a condition to filter output. e.g. 'FieldName = DesiredValue' would return entries where FieldName has DesiredValue value only.
Order refers exact/valid values as mysql query accepts and is used to sort data selection. example value can be 'FieldName ASC' or 'FieldName DESC'.
* #param unknown $operationType
* Possible Values - READ, INSERT, UPDATE, DELETE
* #param unknown $outputFormat
* Possible Values - ASSOC, NUM_ARR, NUM_ROWS
*/
function DB_SSRV_Transact($fieldValueArray, $operationType, $outputFormat) {
$perform_Database_Operation = SSRV_Handle();
$perform_Database_Operation->transact($fieldValueArray, $operation, $outputFormat);
}
/*=====================================================Close mysql connection or destroy mysqli object==============================================================*/
/*
* #access public
*/
function DB_Close()
{
$perform_Database_Operation = DBMgr_Handle();
$perform_Database_Operation->closeConnection();
global $perform_Database_Operation;
$perform_Database_Operation = null;
return;
}
?>
Something on these lines:
This is abstraction that uses mysqli extensions of php
CALL THIS FILE : DbMgr.php
<?php
class DBMgr{
private $mysql_Host, $Port, $userName, $passWord, $DatabaseName, $connection, $dbType;
//Constructor function to connect and select database.
/*
* The argument is a assoc array with possible following structure
* array(
* 'source' => 'value is a string. Possible values are Func/Coded', Default value is Func. For Func, the application must have already defined a functiobn name get_DbConfig, which will return assoc array with following structure,
* array(
* 'host' => '',
* 'port' => '',
* 'username' => '',
* 'password' => '',
* 'database' => '',
* 'type' => 'optional. The default value is mysql'
* );
* 'type' => 'mandatory/Required only for Coded Source' Default value is mysql. Other possible values are nssql,postgresql.
* 'host' => 'mandatory/Required only for Coded Source'
* 'port' => 'mandatory/Required only for Coded Source'
* 'username' => 'mandatory/Required only for Coded Source'
* 'password' => 'mandatory/Required only for Coded Source'
* 'database' => 'mandatory/Required only for Coded Source. This is the database name.'
* );
*
*/
function __construct($config)
{
$this->dbType = $config['dbType'];
$this->mysql_Host = $config['host'];
$this->Port = $config['port'];
$this->userName = $config['username'];
$this->passWord = $config['password'];
$this->DatabaseName = $config['database'];
$this->connect_SpecificDatabase();
}
function __destruct() {
$this->connection = null;
}
private function connect_SpecificDatabase(){
if(!isset($this->connection)) {
switch ($this->dbType) {
case 'mysql':
$db = new mysqli('p:'.$this->mysql_Host, $this->userName, $this->passWord, $this->DatabaseName, $this->Port); // Make a connection my MySQL
$this->connection = $db;
break;
case 'postgresql':
// Make a connection to PostgreSQL
$connectionString = "host = '".$this->mysql_Host."' port = '".$this->Port."' dbname = '".$this->DatabaseName."' user='".$this->userName."' password = '".$this->passWord."'";
$db = pg_connect($connection_string);
$this->connection = $db;
break;
}
}
else {
$db = $this->connection;
}
if (!$db)
return "Error: Connection failed '".$this->set_dbError()."'";
}
private function set_dbError($Query, &$DB_OperationError = '')
{
include_once __DIR__.'./../ErrorHandling.php';
$DB_OperationError = "";
global $error_code;
switch ($this->dbType) {
case 'mysql':
$DB_OperationError = mysqli_error($this->connection);
$error_code = mysqli_errno($this->connection);
break;
case 'mssql':
$DB_OperationError = mssql_get_last_message();
break;
case 'postgresql':
$DB_OperationError = pg_last_error($this->connection);
break;
}
ErrorLogging('query: --'.$Query.' -- '.'Error: --'.$DB_OperationError);
}
private function FieldValuePair_ToString($FieldValueArray,$onlyValueString=false)
{
$FieldsAsString = "";
foreach ($FieldValueArray as $FieldName => $value) {
if($FieldsAsString != "")
$FieldsAsString .= ', ';
/* if(strpos($value, '+') > 0 || strpos($value, '-') > 0)
$FieldsAsString .= $FieldName." = ".$value;
*/
if(strpos($value,'\'') !== false || strpos($value,'\"') !== false) {
$value = addslashes($value);
}
if($onlyValueString){
if($value != 'now()')
$FieldsAsString .= "'".$value."'";
else
$FieldsAsString .= $value;
}
else{
if($value != 'now()')
$FieldsAsString .= $FieldName." = '".$value."'";
else
$FieldsAsString .= $FieldName." = ".$value;
}
}
return $FieldsAsString;
}
public function Prepare_Output($output, $output_Format, $keyField_Output = '')
{
$output_Format = strtolower($output_Format); // Convert output_Format to lowercase
if(!is_object($output))
return $output;
elseif($output->num_rows == 0)
return 0;
switch($output_Format)
{
case 'result':
return $output;
break;
case 'num_rows':
return $output->num_rows;
break;
case 'num_arr':
while ($row = $output->fetch_array(MYSQLI_NUM)) {
$output_arr[] = $row;
}
return $output_arr;
break;
case 'assoc':
default:
while ($row = $output->fetch_assoc()) {
if($keyField_Output != '' && isset($row[$keyField_Output])){
$output_arr[strval($row[$keyField_Output])] = $row;
}
else
$output_arr[] = $row;
}
return $output_arr;
break;
}
}
private function Prepare_Query($input_array, $prepare_For)
{
$Query = "";
switch($prepare_For)
{
case 'READ':
if($input_array['Fields'] == "" || $input_array['Fields'] == NULL || $input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "SELECT ";
$Query .= $input_array['Fields'];
$Query .= " FROM ";
$Query .= $input_array['Table'];
if(isset($input_array['clause']) && $input_array['clause'] != "" && $input_array['clause'] !== NULL)
{
$Query .= " WHERE ";
$Query .= $input_array['clause'];
}
if(isset($input_array['order']) && $input_array['order'] != "" && $input_array['order'] !== NULL)
{
$Query .= " ORDER BY ";
$Query .= $input_array['order'];
}
break;
case 'INSERT':
if($input_array['Fields'] == "" || $input_array['Fields'] == NULL || $input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "INSERT INTO ";
$Query .= $input_array['Table'];
$Query .= " SET ";
$Query .= $this->FieldValuePair_ToString($input_array['Fields']);
break;
case 'UPDATE':
if($input_array['Fields'] == "" || $input_array['Fields'] == NULL || $input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "UPDATE ";
$Query .= $input_array['Table'];
$Query .= " SET ";
$Query .= $this->FieldValuePair_ToString($input_array['Fields']);
if(isset($input_array['clause']) && $input_array['clause'] != "" && $input_array['clause'] !== NULL)
{
$Query .= " WHERE ";
$Query .= $input_array['clause'];
}
break;
case 'DELETE':
if($input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "DELETE FROM ";
$Query .= $input_array['Table']."";
if($input_array['clause'] != "" && $input_array['clause'] !== NULL)
{
$Query .= " WHERE ";
$Query .= $input_array['clause'];
}
break;
case 'INSERT_MR':
$vstring = ""; // Field String
if(is_array($input_array)) {
$tableName = $input_array['TABLE_NAME'];
$input_array = $input_array['FIELD_ARRAY'];
for($i = 0 ;$i < count($input_array); $i++) {
$vstring .= "(" . $this->FieldValuePair_ToString($input_array[$i],true) . ")";
if(! ($i == (count($input_array) - 1))) $vstring .= ",";
}
// Column String
$column_string = implode("," , array_keys($input_array[0])); // Get the column names
$Query = "INSERT INTO ".$tableName." (" . $column_string . ") VALUES ".$vstring.";"; // Form Query String
}
break;
case 'IMPORT_DB':
if(is_array($input_array)) {
$completePathOfSQLFile = "\"" . $input_array['COMPLETE_PATH'];
$Query = "mysql --user" . $this->userName . " --password " . $this->DatabaseName . " < " . $completePathOfSQLFile;
}
break;
case 'EXPORT_DB':
if(is_array($input_array)) {
$TableArray = $input_array['TABLE_LIST'];
$dumpFileName = $input_array['DUMP_FILE_NAME'];
$dQuery = "mysqldump -h ".$this->mysql_Host." --port=".$this->Port." --user=".$this->userName." --password=".$this->passWord;
$dumpFilePath = __DIR__;
$dumpFileName = $dumpFileName == "" ? time().'mysqlDump.sql': $dumpFileName;
if(($TableArray == null) || count($TableArray) == 0 ) {
// Export all tables
$Query = $dQuery . " --databases ".$this->DatabaseName." > ".$dumpFilePath."\\".$dumpFileName;
} else {
$tableNames = "";
// Export selective tables
foreach($TableArray as $k => $k_value) {
$tableNames .= " " . $$TableArray[$k];
}
$Query = $dQuery . " " . $this->DatabaseNames." " . $tableNames . " > \"" . $dumpFilePath."\\".$dumpFileName."\"";
}
}
break;
}
return $Query;
}
public function Read($input_array, $outputFormat, $DataType = "", $keyField_Output = '')
{
$Query = $this->Prepare_Query($input_array, 'READ');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = $this->Prepare_Output($result, $outputFormat, $keyField_Output);
if( ($DataType != "") && (strcasecmp(strtolower($DataType) , 'as_json') == 0) )
$output = json_encode($output);
}
}
return $output;
}
public function Insert($input_array)
{
$Query = $this->Prepare_Query($input_array, 'INSERT');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = mysqli_insert_id($this->connection);
if(!$output)
return true;
}
}
return $output;
}
public function Update($input_array)
{
$Query = $this->Prepare_Query($input_array, 'UPDATE');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = true;
}
}
return $output;
}
public function Delete($input_array)
{
$Query = $this->Prepare_Query($input_array, 'DELETE');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = true;
}
}
return $output;
}
public function Query($Query, $outputFormat = 'ASSOC', $DataType = "", $keyField_Output = '')
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = $this->Prepare_Output($result, $outputFormat, $keyField_Output);
if($DataType != "")
$output = json_encode($output);
}
return $output;
}
public function Export($ExportDBArray) {
$Query = $this->Prepare_Query($input_array, 'EXPORT_DB');
$op = '';
$REtVal = '';
$query = 'dir';
$resultQuery = exec($query,$op,$REtVal);
if($resultQuery) return true;
else return false;
}
public function Import($ImportDBArray) {
$Query = $this->Prepare_Query($ImportDBArray, 'IMPORT_DB');
$resultQuery = exec($Query);
}
public function InsertMR($multipleFieldsArray) {
$tableName = $multipleFieldsArray['TABLE_NAME'];
$listOfID = $multipleFieldsArray['ID_LIST'];
$FieldsArray = $multipleFieldsArray['FIELD_DETAILS'];
$input_array = array('FIELD_ARRAY' => $FieldsArray, 'TABLE_NAME' => $tableName);
$Query = $this->Prepare_Query($input_array, 'INSERT_MR');
$result = $this->connection->query($Query); // Run Query
$output = array();
if (!$result) {
$this->set_dbError($Query);
} else {
$insert_id = mysqli_insert_id($this->connection);
if($listOfID) {
for($i=0; $i<count($FieldsArray); $i++) {
$output[$i] = $insert_id;
$insert_id++;
}
} else {
$output[0] = $insert_id;
}
}
return $output;
}
public function closeConnection() {
if(isset($this->connection)) {
mysqli_close($this->connection);
}
}
};
?>
I have setup magmi with item disabler. And i got PHP notice: Undefined index: ITEM_SID in /home/mywebsite/www/public_html/magmi/plugins/extra/itemprocessors/itemdisabler/magmi_itemdisabler_plugin.php on line 65
This is the my code for item disabler
<?php class Magmi_ItemdisablerPlugin extends Magmi_GeneralImportPlugin {
protected $_dcols=array();
protected $magentoSortableAttributes = array();
public function getPluginInfo()
{
return array("name"=>"Magmi Magento Item Disabler",
"author"=>"RIS",
"version"=>"1.0.0");
}
public function afterImport()
{
$this->log("Running Item Disabler Plugin","info");
$this->disableItems();
return true;
}
public function getPluginParams($params)
{
return array();
}
public function isRunnable()
{
return array(true,"");
}
public function initialize($params)
{
}
public function disableItems()
{
$this->datasource = $this->getDataSource();
$nitems=$this->lookup();
if($nitems>0)
{
$datasource_item_sids = array();
$this->resetSkuStats();
//intialize store id cache
$this->callPlugins("datasources,itemprocessors","startImport");
//initializing item processors
$cols=$this->datasource->getColumnNames();
$this->log(count($cols),"columns");
//$this->callPlugins("itemprocessors","processColumnList",$cols);
//Pack the datasource sids into an array
$i = 0;
while(($item=$this->datasource->getNextRecord())!==false && $i++ <= $nitems)
{
if (isset($item['STYLE_SID']) && $this->isConfigurable($item['ATTR']))
{
array_push($datasource_item_sids, $item['STYLE_SID']);
}
array_push($datasource_item_sids, $item['ITEM_SID']);
if($i == $nitems) {
break;
}
}
if(count($datasource_item_sids) > 0) {
//Convert skus to comma seperated values.
//$datasource_item_sids = "'" . implode("','",$datasource_item_sids) . "'";
//Load in Database Helpers
require_once(realpath(dirname( __FILE__ ) )."/../../../../inc/dbhelper.class.php");
//var_dump($this->_magmiconfig->load()->get("DATABASE","host","localhost"));
$db = new DBHelper();
$host=$this->_magmiconfig->load()->get("DATABASE","host","localhost");
$dbname=$this->_magmiconfig->load()->get("DATABASE","dbname","magento");
$user=$this->_magmiconfig->load()->get("DATABASE","user");
$pass=$this->_magmiconfig->load()->get("DATABASE","password");
$debug=$this->_magmiconfig->load()->get("DATABASE","debug");
$conn=$this->_magmiconfig->load()->get("DATABASE","connectivity","net");
$port=$this->_magmiconfig->load()->get("DATABASE","port","3306");
$socket=$this->_magmiconfig->load()->get("DATABASE","unix_socket");
$prefix=$this->_magmiconfig->load()->get("DATABASE","table_prefix");
$db->initDb($host,$dbname,$user,$pass,$port,$socket,$conn,$debug);
//Setup tables
$ea = $prefix!=""?$prefix."eav_attribute":"eav_attribute";
$cpe = $prefix!=""?$prefix."catalog_product_entity":"catalog_product_entity";
$cpei = $prefix!=""?$prefix."catalog_product_entity_int":"catalog_product_entity_int";
//Get "status" attribute_id
$status_attr_id = "SELECT attribute_id FROM $ea WHERE attribute_code = 'status'";
$result = $db->selectAll($status_attr_id);
if (count($result) == 1) {
$attribute_id = $result[0]['attribute_id'];
}
unset($result);
//Get all active items
$sql = "SELECT e.sku, e.entity_id FROM $cpei i
INNER JOIN $cpe e ON
e.entity_id = i.entity_id
WHERE attribute_id=?
AND i.value = 1";
$all_magento_items = $db->selectAll($sql, array($attribute_id));
//Setup the magento_skus array for easy processing.
$magento_skus = array();
foreach($all_magento_items as $item)
{
$magento_skus[$item['sku']] = $item['entity_id'];
}
//process the array, move anything thats in the datasource.
foreach($datasource_item_sids as $sku)
{
if(isset($magento_skus[$sku]))
{
unset($magento_skus[$sku]);
}
}
if(!empty($magento_skus))
{
foreach($magento_skus as $sku => $id)
{
$this->log("Disabling Item Id $id with SKU: $sku", "info");
$this->update("
UPDATE $cpei i
INNER JOIN $cpe e ON
e.entity_id = i.entity_id
SET VALUE = '2'
WHERE attribute_id = ?
AND i.value = 1
AND e.sku=?", array($attribute_id, $sku));
}
}
else
{
//If the Datasource contains all Magento's items.
$this->log('All items present in datasource. No items to disable.', "info");
}
$db->exitDb();
unset($db);
}
}
}
public function isConfigurable($field) {
$attributes = explode('|',$field);
$conf_attributes = '';
foreach($attributes as $attribut) {
$att = explode(':',$attribut);
if(count($att) != 2) {
return false;
break;
}
if($att[1] == '') {
return false;
break;
}
}
return true;
}
}
Any idea how i can resolve this?
You can check if that element is set before using it:
while(($item=$this->datasource->getNextRecord())!==false && $i++ <= $nitems)
{
if (isset($item['STYLE_SID']) && $this->isConfigurable($item['ATTR']))
{
array_push($datasource_item_sids, $item['STYLE_SID']);
}
if (isset($item['ITEM_SID']){
array_push($datasource_item_sids, $item['ITEM_SID']);
}
if($i == $nitems) {
break;
}
}
Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>