How to do robust PHP database modeling - php

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);
}
}
};
?>

Related

Custom Joomla profile plugin registered user database table update issues

I have a custom extension that uses the Joomla profile plugin and extends it to provide additional fields to the user profile in the administrator panel and in the registered area on the front end of the website. The fields are set to display to admins-only, be disabled, be optional or be required. When they are set to admin-only, they do not show on the front end of the website in the "edit your profile" form. The plugin handles the UPDATE command for all fields with no issues in the administrator panel, but when the UPDATE command is triggered by a user updating their profile on the front end, all of the admin-only fields are overwritten with empty values. All of the other fields, whether they are optional or required are successfully saved or maintained in the form. I have included the custom profile plugin's PHP code below.
<?php
/**
* #package Joomla.Plugin
* #subpackage User.profile
*
* #copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_BASE') or die;
/**
* An example custom profile plugin.
*
* #since 1.6
*/
class PlgUserKiduka extends JPlugin
{
/**
* Load the language file on instantiation.
*
* #var boolean
* #since 3.1
*/
protected $autoloadLanguage = true;
/**
* Constructor
*
* #param object &$subject The object to observe
* #param array $config An array that holds the plugin configuration
*
* #since 1.5
*/
public function __construct(& $subject, $config)
{
parent::__construct($subject, $config);
JFormHelper::addFieldPath(__DIR__ . '/fields');
}
/**
* Runs on content preparation
*
* #param string $context The context for the data
* #param object $data An object containing the data for the form.
*
* #return boolean
*
* #since 1.6
*/
public function onContentPrepareData($context, $data)
{
// No need to display the context variable as a heading on the registration page
// echo '<h1>'.$context.'</h1>';
// Check we are manipulating a valid form.
if (!in_array($context, array('com_users.profile', 'com_users.user', 'com_users.registration', 'com_admin.profile')))
{
return true;
}
if (is_object($data))
{
$userId = isset($data->id) ? $data->id : 0;
if ($userId > 0)
{
// Load the profile data from the database.
$db = JFactory::getDbo();
$db->setQuery(
'SELECT * FROM #__kiduka_accounts WHERE user_id = ' . $userId
);
$data->kiduka = $db->loadObject();
}
}
return true;
}
/**
* adds additional fields to the user editing form
*
* #param JForm $form The form to be altered.
* #param mixed $data The associated data for the form.
*
* #return boolean
*
* #since 1.6
*/
public function onContentPrepareForm($form, $data)
{
if (!($form instanceof JForm))
{
$this->_subject->setError('JERROR_NOT_A_FORM');
return false;
}
// Check we are manipulating a valid form.
$name = $form->getName();
if (!in_array($name, array('com_admin.profile', 'com_users.user', 'com_users.profile', 'com_users.registration')))
{
return true;
}
foreach(JFactory::getUser()->get('groups') as $group){
if(in_array($group, $this->params->get('usergroup'))){
return true;
}
}
// Add the registration fields to the form.
JForm::addFormPath(__DIR__ . '/profiles');
$form->loadFile('profile', false);
$fields = array(
'firechief',
'title',
'membership_no',
'organization',
'organizationtype',
'membertype',
'afcaregion',
'municipalcode',
'membershipyear',
'address1',
'address2',
'city',
'province',
'postalcode',
'country',
'businessphone',
'homephone',
'cellphone',
'fax',
'notes',
'gstexempt',
'billorganization',
'billaddress1',
'billaddress2',
'billcity',
'billprovince',
'billpostalcode',
'billcountry'
);
// Change fields description when displayed in front-end or back-end profile editing
$app = JFactory::getApplication();
foreach ($fields as $field)
{
// Case using the users manager in admin
if ($name == 'com_users.user')
{
// Toggle whether the field is required.
if ($this->params->get('profile-require_' . $field, 1) > 0 || $this->params->get('profile-require_' . $field, 1) == -1)
{
$form->setFieldAttribute($field, 'required', ($this->params->get('profile-require_' . $field) == 2) ? 'required' : '', 'kiduka');
}
else
{
$form->removeField($field, 'kiduka');
}
}
// Case registration
elseif ($name == 'com_users.registration')
{
// Toggle whether the field is required.
if ($this->params->get('register-require_' . $field, 1) > 0)
{
$form->setFieldAttribute($field, 'required', ($this->params->get('register-require_' . $field) == 2) ? 'required' : '', 'kiduka');
}
else
{
$form->removeField($field, 'kiduka');
}
}
// Case profile in site or admin
elseif ($name == 'com_users.profile' || $name == 'com_admin.profile')
{
// Toggle whether the field is required.
if ($this->params->get('profile-require_' . $field, 1) > 0)
{
$form->setFieldAttribute($field, 'required', ($this->params->get('profile-require_' . $field) == 2) ? 'required' : '', 'kiduka');
}
else
{
$form->removeField($field, 'kiduka');
}
}
}
return true;
}
/**
* saves user profile data
*
* #param array $data entered user data
* #param boolean $isNew true if this is a new user
* #param boolean $result true if saving the user worked
* #param string $error error message
*
* #return bool
*/
public function onUserAfterSave($data, $isNew, $result, $error)
{
$user = JFactory::getUser();
$modified_by = $user->get('id');
$userId = JArrayHelper::getValue($data, 'id', 0, 'int');
$datenow = JFactory::getDate();
$modified = $datenow->toSql();
$fields = array(
// 'membership_no',
'title',
'firechief',
'organization',
'address1',
'address2',
'city',
'province',
'postalcode',
'country',
'businessphone',
'homephone',
'cellphone',
'fax',
'organizationtype',
'membertype',
'billorganization',
'billaddress1',
'billaddress2',
'billcity',
'billprovince',
'billpostalcode',
'billcountry',
'afcaregion',
'gstexempt',
'notes',
'municipalcode',
'membershipyear'
);
if($isNew){
$query = 'INSERT INTO #__kiduka_accounts VALUES(NULL, '.$userId.', "", '.$userId.', '.$userId;
foreach($fields as $field){
$query .= ', "'.$data['kiduka'][$field].'"';
}
$query .= ')';
}else{
$query = 'UPDATE #__kiduka_accounts SET ';
$query .= 'modified = "'.$modified.'", ';
$query .= 'modified_by = "'.$modified_by.'", ';
$query .= 'membership_no = "'.$userId.'", ';
for($i = 0; $i < count($fields); $i++){
$query .= $fields[$i] . ' = "'.$data['kiduka'][$fields[$i]].'"';
if($i < count($fields) - 1){
$query .= ', ';
}
}
$query .= ' WHERE user_id = "'.$userId.'"';
}
// var_dump($data);
// die();
$db = JFactory::getDbo();
$db->setQuery($query);
$db->query();
// var_dump($query);
// die();
return true;
}
public function onUserAfterDelete($user, $success, $msg)
{
if (!$success)
{
return false;
}
$userId = JArrayHelper::getValue($user, 'id', 0, 'int');
if ($userId)
{
try
{
$db = JFactory::getDbo();
$db->setQuery(
'DELETE FROM #__kiduka_accounts WHERE user_id = ' . $userId);
$db->execute();
}
catch (Exception $e)
{
$this->_subject->setError($e->getMessage());
return false;
}
}
return true;
}
}
#Elin I have figured it out. It was suggested on the Joomla forum to use two $fields arrays, one for the front-end profile form and another with all of the fields for the administrator user manager profile form. I have included the PHP code for the onUserAfterSave function below. The if($app->isSite()) if/else shows the limited fields on the front-end profile form and the full list of fields on the administrator profile form.
public function onUserAfterSave($data, $isNew, $result, $error)
{
$app = JFactory::getApplication();
$user = JFactory::getUser();
$modified_by = $user->get('id');
$userId = JArrayHelper::getValue($data, 'id', 0, 'int');
$datenow = JFactory::getDate();
$modified = $datenow->toSql();
if($app->isSite())
{
$fields = array(
'address1',
'address2',
'city',
'province',
'postalcode',
'country',
'businessphone',
'homephone',
'cellphone',
'fax'
);
}
else
{
$fields = array(
'firechief',
'title',
'organization',
'organizationtype',
'membertype',
'afcaregion',
'municipalcode',
'membershipyear',
'address1',
'address2',
'city',
'province',
'postalcode',
'country',
'businessphone',
'homephone',
'cellphone',
'fax',
'notes',
'gstexempt',
'billorganization',
'billaddress1',
'billaddress2',
'billcity',
'billprovince',
'billpostalcode',
'billcountry'
);
}
if($isNew)
{
$db = JFactory::getDbo();
$query = 'INSERT INTO #__kiduka_accounts VALUES(NULL, '.$userId.', "", '.$userId.', '.$userId;
foreach($fields as $field)
{
$query .= ', "'.$data['kiduka'][$field].'"';
}
$query .= ')';
}
else
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query .= 'UPDATE #__kiduka_accounts SET ';
$query .= 'modified = "'.$modified.'", ';
$query .= 'modified_by = "'.$modified_by.'", ';
$query .= 'membership_no = "'.$userId.'", ';
for($i = 0; $i < count($fields); $i++)
{
$query .= $fields[$i] . ' = "'.$data['kiduka'][$fields[$i]].'"';
if($i < count($fields) - 1)
{
$query .= ', ';
}
}
$query .= ' WHERE user_id = "'.$userId.'"';
}
$db->setQuery($query);
$db->execute();
return true;
}

PHP load classes

I have a class loader like this :
function __autoload($classname){
require_once CLASSES_DIR . "/" . $classname . ".class.php";
}
and it correctly sets the URL of any classes.
The problem is that when an instance of a class is tried to be created in the index.php (line 13):
$pdo = PDOWrapper::instance();
The browser shows a page like this:
validateDriver($driver)) { throw new Exception('DATABASE WRAPPER::error, the database you wish to connect to is not supported by your install of PHP.'); } if (isset($this->pdo_master)) { error_log('DATABASE WRAPPER::warning, attempting to config master after connection exists'); } $this->config_master = array( 'driver' => $driver, 'host' => $host, 'name' => $name, 'user' => $user, 'password' => $password, 'port' => $port ); } /** * method configSlave * - configure a connection to a slave (can be called multiple times) * * #param host - the host name of the db to connect to * #param name - the database name * #param user - the user name * #param password - the users password * #param port (optional) - the port to connect using, default to 3306 * #param driver - the dsn prefix */ public function configSlave($host, $name, $user, $password, $port=null, $driver='mysql') { if (!$this->validateDriver($driver)) { throw new Exception('DATABASE WRAPPER::error, the database you wish to connect to is not supported by your install of PHP.'); } if (isset($this->pdo_slave)) { error_log('DATABASE WRAPPER::warning, attempting to config slave after connection exists'); } if (!isset($this->config_slaves)) { $this->config_slaves = array(); } $this->config_slaves[] = array( 'driver' => $driver, 'host' => $host, 'name' => $name, 'user' => $user, 'password' => $password, 'port' => $port ); } /** * method createConnection. * - create a PDO connection using the credentials provided * * #param driver - the dsn prefix * #param host - the host name of the db to connect to * #param name - the database name * #param user - the user name * #param password - the users password * #param port (optional) - the port to connect using, default to 3306 * #return PDO object with a connection to the database specified */ protected function createConnection($driver, $host, $name, $user, $password, $port=null) { die( var_dump(PDO::getAvailableDrivers())); if (!$this->validateDriver($driver)) { throw new Exception('DATABASE WRAPPER::error, the database you wish to connect to is not supported by your install of PHP.'); } // attempt to create pdo object and connect to the database try { //#TODO the following drivers are NOT supported yet: odbc, ibm, informix, 4D // build the connection string from static constants based on the selected PDO Driver. if ($driver == "sqlite" || $driver == "sqlite2") { $connection_string = $driver.':'.$host; } elseif ($driver == "sqlsrv") { $connection_string = "sqlsrv:Server=".$host.";Database=".$name; } elseif ($driver == "firebird" || $driver == "oci") { $connection_string = $driver.":dbname=".$name; } else { $connection_string = $driver.':host='.$host.';dbname='.$name; } // add the port if one was specified if (!empty($port)) { $connection_string .= "port=$port"; } // initialize the PDO object $new_connection = new PDO($connection_string, $user, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); // set the error mode $new_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // return the new connection return $new_connection; } // handle any exceptions by catching them and returning false catch (PDOException $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } catch(Exception $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } } /** * method getMaster. * - grab the PDO connection to the master DB */ protected function getMaster() { // if we have not been configured, use hard coded values if (!isset($this->config_master)) { $this->config_master = array( 'driver' => self::DB_DSN_PREFIX_MASTER, 'host' => self::DB_HOST_MASTER, 'name' => self::DB_NAME_MASTER, 'user' => self::DB_USER_MASTER, 'password' => self::DB_PASSWORD_MASTER, 'port' => self::DB_PORT_MASTER ); } // if we have not created the master db connection yet, create it now if (!isset($this->pdo_master)) { $this->pdo_master = $this->createConnection( $this->config_master['driver'], $this->config_master['host'], $this->config_master['name'], $this->config_master['user'], $this->config_master['password'], $this->config_master['port'] ); } return $this->pdo_master; } /** * method getSlave. * - grab the PDO connection to the slave DB, create it if not there */ protected function getSlave() { // if we have not created a slave db connection, create it now if (!isset($this->pdo_slave)) { // if no slaves were configured, use hardcoded values if (!isset($this->config_slaves)) { $i = 1; while (defined('self::SLAVE' . $i . '_HOST') && constant('self::SLAVE' . $i . '_HOST')) { $this->config_slaves[] = array( 'driver' => constant('self::SLAVE' . $i . '_DSN_PREFIX'), 'host' => constant('self::SLAVE' . $i . '_HOST'), 'name' => constant('self::SLAVE' . $i . '_NAME'), 'user' => constant('self::SLAVE' . $i . '_USER'), 'password' => constant('self::SLAVE' . $i . '_PASSWORD'), 'port' => constant('self::SLAVE' . $i . '_PORT'), ); $i++; } } // if no slaves are configured, use the master connection if (empty($this->config_slaves)) { $this->pdo_slave = $this->getMaster(); } // if we have slaves, randomly choose one to use for this request and connect else { $random_slave = $this->config_slaves[array_rand($this->config_slaves)]; $this->pdo_slave = $this->createConnection( $random_slave['driver'], $random_slave['host'], $random_slave['name'], $random_slave['user'], $random_slave['password'], $random_slave['port'] ); } } return $this->pdo_slave; } /** * method select. * - retrieve information from the database, as an array * * #param string $table - the name of the db table we are retreiving the rows from * #param array $params - associative array representing the WHERE clause filters * #param int $limit (optional) - the amount of rows to return * #param int $start (optional) - the row to start on, indexed by zero * #param array $order_by (optional) - an array with order by clause * #param bool $use_master (optional) - use the master db for this read * #return mixed - associate representing the fetched table row, false on failure */ public function select($table, $params = null, $limit = null, $start = null, $order_by=null, $use_master = false) { // building query string $sql_str = "SELECT * FROM $table"; // append WHERE if necessary $sql_str .= ( count($params)>0 ? ' WHERE ' : '' ); $add_and = false; // add each clause using parameter array if (empty($params)) { $params = array(); } foreach ($params as $key=>$val) { // only add AND after the first clause item has been appended if ($add_and) { $sql_str .= ' AND '; } else { $add_and = true; } // append clause item $sql_str .= "$key = :$key"; } // add the order by clause if we have one if (!empty($order_by)) { $sql_str .= ' ORDER BY'; $add_comma = false; foreach ($order_by as $column => $order) { if ($add_comma) { $sql_str .= ', '; } else { $add_comma = true; } $sql_str .= " $column $order"; } } // now we attempt to retrieve the row using the sql string try { // decide which database we are selecting from $pdo_connection = $use_master ? $this->getMaster() : $this->getSlave(); $pdoDriver = $pdo_connection->getAttribute(PDO::ATTR_DRIVER_NAME); //#TODO MS SQL Server & Oracle handle LIMITs differently, for now its disabled but we should address it later. $disableLimit = array("sqlsrv", "mssql", "oci"); // add the limit clause if we have one if (!is_null($limit) && !in_array($pdoDriver, $disableLimit)) { $sql_str .= ' LIMIT '.(!is_null($start) ? "$start, ": '')."$limit"; } $pstmt = $pdo_connection->prepare($sql_str); // bind each parameter in the array foreach ($params as $key=>$val) { $pstmt->bindValue(':'.$key, $val); } $pstmt->execute(); // now return the results, depending on if we want all or first row only if ( !is_null($limit) && $limit == 1 ) { return $pstmt->fetch(PDO::FETCH_ASSOC); } else { return $pstmt->fetchAll(PDO::FETCH_ASSOC); } } catch(PDOException $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } catch(Exception $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } } /** * method selectMaster. * - retrieve information from the master database, as an array * * #param table - the name of the db table we are retreiving the rows from * #param params - associative array representing the WHERE clause filters * #param int $limit (optional) - the amount of rows to return * #param int $start (optional) - the row to start on, indexed by zero * #param array $order_by (optional) - an array with order by clause * #return mixed - associate representing the fetched table row, false on failure */ public function selectMaster($table, $params = array(), $limit = null, $start = null, $order_by=null) { return $this->select($table, $params, $limit, $start, $order_by, true); } /** * method selectFirst. * - retrieve the first row returned from a select statement * * #param table - the name of the db table we are retreiving the rows from * #param params - associative array representing the WHERE clause filters * #param array $order_by (optional) - an array with order by clause * #return mixed - associate representing the fetched table row, false on failure */ public function selectFirst($table, $params = array(), $order_by=null) { return $this->select($table, $params, 1, null, $order_by); } /** * method selectFirstMaster. * - retrieve the first row returned from a select statement using the master database * * #param table - the name of the db table we are retreiving the rows from * #param params - associative array representing the WHERE clause filters * #param array $order_by (optional) - an array with order by clause * #return mixed - associate representing the fetched table row, false on failure */ public function selectFirstMaster($table, $params = array(), $order_by=null) { return $this->select($table, $params, 1, null, $order_by, true); } /** * method delete. * - deletes rows from a table based on the parameters * * #param table - the name of the db table we are deleting the rows from * #param params - associative array representing the WHERE clause filters * #return bool - associate representing the fetched table row, false on failure */ public function delete($table, $params = array()) { // building query string $sql_str = "DELETE FROM $table"; // append WHERE if necessary $sql_str .= ( count($params)>0 ? ' WHERE ' : '' ); $add_and = false; // add each clause using parameter array foreach ($params as $key=>$val) { // only add AND after the first clause item has been appended if ($add_and) { $sql_str .= ' AND '; } else { $add_and = true; } // append clause item $sql_str .= "$key = :$key"; } // now we attempt to retrieve the row using the sql string try { $pstmt = $this->getMaster()->prepare($sql_str); // bind each parameter in the array foreach ($params as $key=>$val) { $pstmt->bindValue(':'.$key, $val); } // execute the delete query $successful_delete = $pstmt->execute(); // if we were successful, return the amount of rows updated, otherwise return false return ($successful_delete == true) ? $pstmt->rowCount() : false; } catch(PDOException $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } catch(Exception $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } } /** * method update. * - updates a row to the specified table * * #param string $table - the name of the db table we are adding row to * #param array $params - associative array representing the columns and their respective values to update * #param array $wheres (Optional) - the where clause of the query * #param bool $timestamp_this (Optional) - if true we set date_created and date_modified values to now * #return int|bool - the amount of rows updated, false on failure */ public function update($table, $params, $wheres=array(), $timestamp_this=null) { if (is_null($timestamp_this)) { $timestamp_this = self::$TIMESTAMP_WRITES; } // build the set part of the update query by // adding each parameter into the set query string $add_comma = false; $set_string = ''; foreach ($params as $key=>$val) { // only add comma after the first parameter has been appended if ($add_comma) { $set_string .= ', '; } else { $add_comma = true; } // now append the parameter $set_string .= "$key=:param_$key"; } // add the timestamp columns if neccessary if ($timestamp_this === true) { $set_string .= ($add_comma ? ', ' : '') . 'date_modified='.time(); } // lets add our where clause if we have one $where_string = ''; if (!empty($wheres)) { // load each key value pair, and implode them with an AND $where_array = array(); foreach($wheres as $key => $val) { $where_array[] = "$key=:where_$key"; } // build the final where string $where_string = 'WHERE '.implode(' AND ', $where_array); } // build final update string $sql_str = "UPDATE $table SET $set_string $where_string"; // now we attempt to write this row into the database try { $pstmt = $this->getMaster()->prepare($sql_str); // bind each parameter in the array foreach ($params as $key=>$val) { $pstmt->bindValue(':param_'.$key, $val); } // bind each where item in the array foreach ($wheres as $key=>$val) { $pstmt->bindValue(':where_'.$key, $val); } // execute the update query $successful_update = $pstmt->execute(); // if we were successful, return the amount of rows updated, otherwise return false return ($successful_update == true) ? $pstmt->rowCount() : false; } catch(PDOException $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } catch(Exception $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } } /** * method insert. * - adds a row to the specified table * * #param string $table - the name of the db table we are adding row to * #param array $params - associative array representing the columns and their respective values * #param bool $timestamp_this (Optional), if true we set date_created and date_modified values to now * #return mixed - new primary key of inserted table, false on failure */ public function insert($table, $params = array(), $timestamp_this = null) { if (is_null($timestamp_this)) { $timestamp_this = self::$TIMESTAMP_WRITES; } // first we build the sql query string $columns_str = '('; $values_str = 'VALUES ('; $add_comma = false; // add each parameter into the query string foreach ($params as $key=>$val) { // only add comma after the first parameter has been appended if ($add_comma) { $columns_str .= ', '; $values_str .= ', '; } else { $add_comma = true; } // now append the parameter $columns_str .= "$key"; $values_str .= ":$key"; } // add the timestamp columns if neccessary if ($timestamp_this === true) { $columns_str .= ($add_comma ? ', ' : '') . 'date_created, date_modified'; $values_str .= ($add_comma ? ', ' : '') . 'UNIX_TIMESTAMP(), UNIX_TIMESTAMP()'; } // close the builder strings $columns_str .= ') '; $values_str .= ')'; // build final insert string $sql_str = "INSERT INTO $table $columns_str $values_str"; // now we attempt to write this row into the database try { $pstmt = $this->getMaster()->prepare($sql_str); // bind each parameter in the array foreach ($params as $key=>$val) { $pstmt->bindValue(':'.$key, $val); } $pstmt->execute(); $newID = $this->getMaster()->lastInsertId(); // return the new id return $newID; } catch(PDOException $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } catch(Exception $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); print_r($e); } $this->pdo_exception = $e; return false; } } /** * method insertMultiple. * - adds multiple rows to a table with a single query * * #param string $table - the name of the db table we are adding row to * #param array $columns - contains the column names * #param bool $timestamp_these (Optional), if true we set date_created and date_modified values to NOW() for each row * #return mixed - new primary key of inserted table, false on failure */ public function insertMultiple($table, $columns = array(), $rows = array(), $timestamp_these = null) { if (is_null($timestamp_these)) { $timestamp_these = self::$TIMESTAMP_WRITES; } // generate the columns portion of the insert statment // adding the timestamp fields if needs be if ($timestamp_these) { $columns[] = 'date_created'; $columns[] = 'date_modified'; } $columns_str = '(' . implode(',', $columns) . ') '; // generate the values portions of the string $values_str = 'VALUES '; $add_comma = false; foreach ($rows as $row_index => $row_values) { // only add comma after the first row has been added if ($add_comma) { $values_str .= ', '; } else { $add_comma = true; } // here we will create the values string for a single row $values_str .= '('; $add_comma_forvalue = false; foreach ($row_values as $value_index => $value) { if ($add_comma_forvalue) { $values_str .= ', '; } else { $add_comma_forvalue = true; } // generate the bind variable name based on the row and column index $values_str .= ':'.$row_index.'_'.$value_index; } // append timestamps if necessary if ($timestamp_these) { $values_str .= ($add_comma_forvalue ? ', ' : '') . time().', '.time(); } $values_str .= ')'; } // build final insert string $sql_str = "INSERT INTO $table $columns_str $values_str"; // now we attempt to write this multi inster query to the database using a transaction try { $this->getMaster()->beginTransaction(); $pstmt = $this->getMaster()->prepare($sql_str); // traverse the 2d array of rows and values to bind all parameters foreach ($rows as $row_index => $row_values) { foreach ($row_values as $value_index => $value) { $pstmt->bindValue(':'.$row_index.'_'.$value_index, $value); } } // now lets execute the statement, commit the transaction and return $pstmt->execute(); $this->getMaster()->commit(); return true; } catch(PDOException $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; $this->getMaster()->rollback(); return false; } catch(Exception $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; $this->getMaster()->rollback(); return false; } } /** * method execute. * - executes a query that modifies the database * * #param string $query - the SQL query we are executing * #param bool $use_master (Optional) - whether or not to use the master connection * #return mixed - the affected rows, false on failure */ public function execute($query, $params=array()) { try { // use the master connection $pdo_connection = $this->getMaster(); // prepare the statement $pstmt = $pdo_connection->prepare($query); // bind each parameter in the array foreach ((array)$params as $key=>$val) { $pstmt->bindValue($key, $val); } // execute the query $result = $pstmt->execute(); // only if return value is false did this query fail return ($result == true) ? $pstmt->rowCount() : false; } catch(PDOException $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } catch(Exception $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } } /** * method query. * - returns data from a free form select query * * #param string $query - the SQL query we are executing * #param array $params - a list of bind parameters * #param bool $use_master (Optional) - whether or not to use the master connection * #return mixed - the affected rows, false on failure */ public function query($query, $params=array(), $use_master=false) { try { // decide which database we are selecting from $pdo_connection = $use_master ? $this->getMaster() : $this->getSlave(); $pstmt = $pdo_connection->prepare($query); // bind each parameter in the array foreach ((array)$params as $key=>$val) { $pstmt->bindValue($key, $val); } // execute the query $pstmt->execute(); // now return the results return $pstmt->fetchAll(PDO::FETCH_ASSOC); } catch(PDOException $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } catch(Exception $e) { if (self::$LOG_ERRORS == true) { error_log('DATABASE WRAPPER::'.print_r($e, true)); } $this->pdo_exception = $e; return false; } } /** * method queryFirst. * - returns the first record from a free form select query * * #param string $query - the SQL query we are executing * #param array $params - a list of bind parameters * #param bool $use_master (Optional) - whether or not to use the master connection * #return mixed - the affected rows, false on failure */ public function queryFirst($query, $params=array(), $use_master=false) { $result = $this->query($query, $params, $use_master); if (empty($result)) { return false; } else { return $result[0]; } } /** * method getErrorMessage. * - returns the last error message caught */ public function getErrorMessage() { if ($this->pdo_exception) return $this->pdo_exception->getMessage(); else return 'Database temporarily unavailable'; } /** * method getError. * - returns the actual PDO exception */ public function getPDOException() { return $this->pdo_exception; } /** * Validate the database in question is supported by your installation of PHP. * #param string $driver The DSN prefix * #return boolean true, the database is supported; false, the database is not supported. */ private function validateDriver($driver) { if (!in_array($driver, PDO::getAvailableDrivers())) { return false; } else { return true; } } /** * Destructor. * - release the PDO db connections */ function __destruct() { unset($this->pdo_master); unset($this->pdo_slave); } }
Notice: Undefined index: language in C:\xampp\htdocs_\config.php on
line 133
Notice: Undefined variable: condo_name in
C:\xampp\htdocs_\language\fr.php on line 319
Notice: Undefined variable: condo_name in
C:\xampp\htdocs_\language\fr.php on line 320
Notice: Undefined variable: condo_name in
C:\xampp\htdocs_\language\fr.php on line 321
Notice: Undefined variable: claim_name in
C:\xampp\htdocs_\language\fr.php on line 327
Notice: Undefined variable: claim_name in
C:\xampp\htdocs_\language\fr.php on line 328
Notice: Undefined variable: tender in
C:\xampp\htdocs_\language\fr.php on line 329
Notice: Undefined variable: condo_name in
C:\xampp\htdocs_\language\fr.php on line 332
Notice: Undefined variable: condo_name in
C:\xampp\htdocs_\language\fr.php on line 333
Notice: Undefined variable: condo_name in
C:\xampp\htdocs_\language\fr.php on line 361
Fatal error: Class 'PDOWrapper' not found in
C:\xampp\htdocs_\index.php on line 13 etc. and a fatal error:
Fatal error: Class 'PDOWrapper' not found in C:\xampp\htdocs_\index.php on line 13.
So it seems strange that it can show some PDOWrapper code content and a fatal error to find it.
I don't know why the class is not found, and the browser shows the content of the class, you can see the write, throw new Exception . . .Etc.

Call to a member function on a non-object in PHP

I am trying to modify a class that I found that is a Steam API class. I want it to work with codeigniter. I keep getting the error in the question title when I call the getProfileData function. Not sure why it's happening. Here is the code:
The library:
<?php
// Disable XML warnings to avoid problems when SteamCommunity is down
libxml_use_internal_errors(true);
// Use SteamUtility to fetch URLs and other stuff
require_once 'SteamUtility.php';
/**
* SteamUser - Representation of any Steam user profile
*
* #category SteamAPI
* #copyright Copyright (c) 2012 Matt Ryder (www.mattryder.co.uk)
* #license GPLv2 License
* #version v1.3
* #link https://github.com/MattRyder/SteamAPI/blob/master/steam/SteamUser.php
* #since Class available since v1.0
*/
class SteamUser {
private $userID;
private $vanityURL;
private $apiKey;
public $info;
/**
* Constructor
* #param mixed $id User's steamID or vanityURL
* #param string $apiKey API key for http://steamcommunity.com/dev/
*/
/**
* GetProfileData
* - Accesses Steam Profile XML and parses the data
*/
function __construct($params){
$userId = $params['userId'];
$this->CI =& get_instance();
$this->CI->load->config('steam');
if(empty($userId)) {
echo "Error: No Steam ID or URL given!", PHP_EOL;
return NULL;
}
if(is_numeric($userId)) {
$this->userID = $userId;
}
else {
$this->vanityURL = strtolower($userId);
}
$this->apiKey = $this->CI->config->item('api_key');
}
function getProfileData() {
$info = array();
//Set Base URL for the query:
if(empty($this->vanityURL)) {
$base = "http://steamcommunity.com/profiles/{$this->userId}/?xml=1";
} else {
$base = "http://steamcommunity.com/id/{$this->vanityURL}/?xml=1";
}
try {
$content = SteamUtility::fetchURL($base);
if ($content) {
$parsedData = new SimpleXMLElement($content);
} else {
return null;
}
} catch (Exception $e) {
//echo "Whoops! Something went wrong!\n\nException Info:\n" . $e . "\n\n";
return null;
}
if(!empty($parsedData)) {
$info['steamID64'] = (string)$parsedData->steamID64;
$info['steamID'] = (string)$parsedData->steamID;
$info['stateMessage'] = (string)$parsedData->stateMessage;
$info['visibilityState'] = (int)$parsedData->visibilityState;
$info['privacyState'] = (string)$parsedData->privacyState;
$info['avatarIcon'] = (string)$parsedData->avatarIcon;
$info['avatarMedium'] = (string)$parsedData->avatarMedium;
$info['avatarFull'] = (string)$parsedData->avatarFull;
$info['vacBanned'] = (int)$parsedData->vacBanned;
$info['tradeBanState'] = (string)$parsedData->tradeBanState;
$info['isLimitedAccount'] = (string)$parsedData->isLimitedAccount;
$info['onlineState'] = (string)$parsedData->onlineState;
$info['inGameServerIP'] = (string)$parsedData->inGameServerIP;
//If their account is public, get that info:
if($info['privacyState'] == "public") {
$info['customURL'] = (string)$parsedData->customURL;
$info['memberSince'] = (string)$parsedData->memberSince;
$info['steamRating'] = (float)$parsedData->steamRating;
$info['hoursPlayed2Wk'] = (float)$parsedData->hoursPlayed2Wk;
$info['headline'] = (string)$parsedData->headline;
$info['location'] = (string)$parsedData->location;
$info['realname'] = (string)$parsedData->realname;
$info['summary'] = (string)$parsedData->summary;
}
//If they're in a game, grab that info:
if($info['onlineState'] == "in-game") {
$info['inGameInfo']['inGameInfo'] = array();
$info['inGameInfo']["gameName"] = (string)$parsedData->inGameInfo->gameName;
$info['inGameInfo']["gameLink"] = (string)$parsedData->inGameInfo->gameLink;
$info['inGameInfo']["gameIcon"] = (string)$parsedData->inGameInfo->gameIcon;
$info['inGameInfo']["gameLogo"] = (string)$parsedData->inGameInfo->gameLogo;
$info['inGameInfo']["gameLogoSmall"] = (string)$parsedData->inGameInfo->gameLogoSmall;
}
//Get their most played video games:
if(!empty($parsedData->mostPlayedGames)) {
$info['mostPlayedGames'] = array();
$i = 0;
foreach ($parsedData->mostPlayedGames->mostPlayedGame as $mostPlayedGame) {
$info['mostPlayedGames'][$i] = new stdClass();
$info['mostPlayedGames'][$i]['gameName'] = (string)$mostPlayedGame->gameName;
$info['mostPlayedGames'][$i]['gameLink'] = (string)$mostPlayedGame->gameLink;
$info['mostPlayedGames'][$i]['gameIcon'] = (string)$mostPlayedGame->gameIcon;
$info['mostPlayedGames'][$i]['gameLogo'] = (string)$mostPlayedGame->gameLogo;
$info['mostPlayedGames'][$i]['gameLogoSmall'] = (string)$mostPlayedGame->gameLogoSmall;
$info['mostPlayedGames'][$i]['hoursPlayed'] = (string)$mostPlayedGame->hoursPlayed;
$info['mostPlayedGames'][$i]['hoursOnRecord'] = (string)$mostPlayedGame->hoursOnRecord;
$info['mostPlayedGames'][$i]['statsName'] = (string)$mostPlayedGame->statsName;
$i++;
}
}
//Any weblinks listed in their profile:
if(!empty($parsedData->weblinks)) {
$this['weblinks'] = array();
$i = 0;
foreach ($parsedData->weblinks->weblink as $weblink) {
$info['weblinks'][$i]['title'] = (string)$weblink->title;
$info['weblinks'][$i]['link'] = (string)$weblink->link;
$i++;
}
}
//And grab any subscribed groups:
if(!empty($parsedData->groups)) {
$this->groups = array();
$i = 0;
foreach ($parsedData->groups->group as $group) {
$info['groups'][$i] = array();
$info['groups'][$i]['groupID64'] = (string)$group->groupID64;
$info['groups'][$i]['groupName'] = (string)$group->groupName;
$info['groups'][$i]['groupURL'] = (string)$group->groupURL;
$info['groups'][$i]['headline'] = (string)$group->headline;
$info['groups'][$i]['summary'] = (string)$group->summary;
$info['groups'][$i]['avatarIcon'] = (string)$group->avatarIcon;
$info['groups'][$i]['avatarMedium'] = (string)$group->avatarMedium;
$info['groups'][$i]['avatarFull'] = (string)$group->avatarFull;
$info['groups'][$i]['memberCount'] = (string)$group->memberCount;
$info['groups'][$i]['membersInChat'] = (string)$group->membersInChat;
$info['groups'][$i]['membersInGame'] = (string)$group->membersInGame;
$info['groups'][$i]['membersOnline'] = (string)$group->membersOnline;
$i++;
}
}
}
return $info;
}
My model where I call it:
function retrieve($member_id = 0){
$info = array();
$this->db->select('memberId AS id, facebookId, steamId, userName, emailAddress, dateJoined, dateBorn')
->from('members')
->where('memberId', $member_id)
->limit(1);
if($query = $this->db->get()){
if($query->num_rows() > 0){
$member = $query->row_array();
var_dump($member);
$info = $member;
if($member['steamId'] != ''){
$this->load->library('SteamUser', array('userId' => $member['steamId']));
$steam = $this->SteamUser->getProfileData();
$info['steam'] = array(
'id' => $member['steamId'],
'avatar' => $steam['avatarIcon']
);
}
}
}
$this->info = $info;
}
Dumping the $member variable returns this:
array (size=7)
'id' => string '11' (length=2)
'facebookId' => string '' (length=0)
'steamId' => string 'STEAM_0:1:000000000' (length=17)
'userName' => string 'John Smith' (length=18)
'emailAddress' => string '' (length=0)
'dateJoined' => string '2015-09-23 19:38:17' (length=19)
'dateBorn' => string '0000-00-00 00:00:00' (length=19)
Try these methods
print_r($member['steamId']); to check data is empty or not.
If you passing data as objective array, then you need to access data with pointing [0],
ex: $this->SteamUser->getProfileData($member[0]['steamId']);
Check aging with print_r
print_r($member[0]['steamId']);
So final code will be
print_r($member['steamId']);//check data exist
print_r($member[0]['steamId']);//check data exist
if($member['steamId'])
{
$this->load->library('SteamUser');
$this->SteamUser->getProfileData($member['steamId']);
$steam = array('id' => $member['steamId'], 'avatar' => $this->SteamUser->avatarIcon);
$info = array_merge($info, $steam);
}
Apparently, when you load a class with CodeIgniter, the name of the object that is given is all lower case. So I was loading $this->SteamUser->getProfileData() when I should have been doing it like $this->steamuser->getProfileData().

Fatal error: Undefined class constant [duplicate]

This question already has answers here:
How to refer to a static constant member variable in PHP
(2 answers)
Closed 10 years ago.
So I'm trying to use this mysqli connection class (code below) but I am receiving the error message: Fatal error: Undefined class constant 'DBUSER' [...] I can't figure out why because I have set all the database connection credentials and included the config file.
My db.config.class.php:
class config {
public static $DBSERVER = "localhost"; // Set the IP or hostname of the database server you wish to connect to
public static $DBNAME = "**REMOVED**"; // Set the name of the database you wish to connect to
public static $DBUSER = "**REMOVED**"; // set the database user name you wish to use to connect to the database server
public static $DBPASSWORD = "**REMOVED**"; // set the password for the username above
public static $DBPORT = 3306;
public static $TABLEPREFIX = "";
}
mysqli.class.php:
include('db.config.class.php');
/**
* My-SQL database class
*
* #name mysql
* #version 2
* #author Leigh Edwards
* #category PHP
*/
class Dbconnect {
// leave blank if used for multiple users and call setUser method
private $sqlUser = "";
// leave blank if used for multiple users and call setPassword method
private $sqlPassword = "";
// set this to the database name you wish to use. If this class is used to access a number of Databases
// leave blank and call the select method to select the desired database
private $sqlDatabase = "";
// set this to the database server address. If you are using this class to connect to differant server
// leave blank and call the setHost method
private $sqlHost = "";
// Set this to the prefix of your tables if you set one while installing.
// default = ""
public $table_prefix = "";
private $result; // Query result
private $querycount; // Total queries executed
private $linkid;
/////////////////////////////////////////END CONFIG OPTIONS/////////////////////////////////////////////////////
function __construct() {
$this->loadDefaults ();
$this->connect ( $this->sqlHost, $this->sqlUser, $this->sqlPassword, $this->sqlDatabase );
$this->select ( $this->sqlDatabase );
}
/*
* method to load the object with the defaut settings
*/
private function loadDefaults() {
$this->sqlUser = config::DBUSER;
$this->sqlPassword = config::DBPASSWORD;
$this->sqlHost = config::DBSERVER;
$this->sqlDatabase = config::DBNAME;
$this->table_prefix = config::TABLEPREFIX;
}
public function getResult() {
return $this->result;
}
/**
* method to return the prefix for the sql tables
*
* #return = string $this->table_prefix
*/
public function get_tablePrefix() {
return $this->table_prefix;
}
/**
* function to return a string from within another string
* found between $beginning and $ending
*
* #param string $source
* #param string $beginning
* #param string $ending
* #param string $init_pos
*/
function get_middle($source, $beginning, $ending, $init_pos) {
$beginning_pos = strpos ( $source, $beginning, $init_pos );
$middle_pos = $beginning_pos + strlen ( $beginning );
$ending_pos = strpos ( $source, $ending, $beginning_pos + 1 );
$middle = substr ( $source, $middle_pos, $ending_pos - $middle_pos );
return $middle;
}
/**
* method to connect to the MySQL database server.
*
* #param string $sqlHost
* #param string $sqlUser
* #param string $sqlPassword
**/
function connect($sqlHost, $sqlUser, $sqlPassword, $sqlDatabase) {
try {
$this->linkid = mysqli_connect ( $sqlHost, $sqlUser, $sqlPassword, $sqlDatabase, 3306 );
if (! $this->linkid) {
die ( 'Connect Error (' . mysqli_connect_errno () . ') ' . mysqli_connect_error () );
}
} catch ( Exception $e ) {
die ( $e->getMessage () );
}
}
/**
* method to select the database to use
* #param string $sqlDatabase
*/
function select($sqlDatabase) {
try {
if (! #mysqli_select_db ( $sqlDatabase, $this->linkid )) {
throw new Exception ( "The Selected Database Can Not Be Found On the Database Server. $sqlDatabase (E2)" );
}
} catch ( Exception $e ) {
die ( $e->getMessage () );
}
}
/**
* method to query sql database
* take mysql query string
* returns false if no results or NULL result is returned by query
* if query action is not expected to return results eg delete
* returns false on sucess else returns result set
*
* NOTE: If you requier the the actual result set call one of the fetch methods
*
* #param string $query
* #return boolian true or false
*/
function query($query) {
// ensure clean results
unset ( $this->result );
// make query
$this->result = mysqli_query ( $query, $this->linkid );
if (! $this->result) {
echo "<br>Query faild: $query";
return FALSE;
} else {
return true;
}
}
/**
* method to return the number of rows affected by the
* last query exicuted
* #return int
*/
function affectedRows() {
$count = mysqli_affected_rows ( $this->linkid );
return $count;
}
/**
* method to return the number of rows in the result set
* returned by the last query
*/
function numRows() {
$count = #mysqli_num_rows ( $this->result );
return $count;
}
/**
* method to return the result row as an object
* #return object
*/
function fetchObject() {
$row = #mysqli_fetch_object ( $this->result );
return $row;
}
/**
* method to return the result row as an indexed array
* #return array
*/
function fetchRow() {
$row = #mysqli_fetch_row ( $this->result );
return $row;
}
/**
* method to return the result row as an associative array.
* #return array
**/
function fetchArray() {
$row = #mysqli_fetch_array ( $this->result, mysqli_ASSOC );
return $row;
}
/**
* method to return total number queries executed during
* the lifetime of this object.
*
* #return int
*/
function numQueries() {
return $this->querycount;
}
function setResult($resultSet) {
$this->result = $resultSet;
}
/**
* method to return the number of fields in a result set
* #return int
**/
function numberFields() {
return #mysqli_num_fields ( $this->result );
}
/**
* method to return a field name given an integer offset
* #return string
**/
function fieldName($offset) {
return #mysqli_field_name ( $this->result, $offset );
}
/**
* method to return the results of the last query
* in html table
*
* This method uses the $actions string to pass html code
* this is added to the table to enable display of images or links
* in the last columb of the table
*
* if boolian false is passed no html is add to the result table
* $startCol sets the col to start displaying 0 being the first
*
* #param int $startCol
* #param string or boolian false $actions
* #return string containing html code to dispay the table
*/
function getResultAsTable($startCol, $actions = "") {
if ($this->numrows () > 0) {
// Start the table
$resultHTML = "<table width=\"80%\" border=\"0\" align=\"center\" cellpadding=\"1\" cellspacing=\"0\"><tr>";
$resultHTML .= "<td><table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"1\"><tr>";
$x = $startCol;
// Output the table header
$fieldCount = $this->numberFields ();
for($i = $x; $i < $fieldCount; $i ++) {
$rowName = $this->fieldName ( $i );
$resultHTML .= "<th align=\"left\">$rowName</th>";
}
if (! $actions === false) {
$resultHTML .= "<th align=\"left\">actions</th>";
}
$resultHTML .= "</tr>";
while ( $row = $this->fetchRow () ) {
$resultHTML .= "<tr>";
for($i = $x; $i < $fieldCount; $i ++)
$resultHTML .= "<td align=\"left\">" . htmlentities ( $row [$i] ) . "</td>";
if (! $actions === false) {
// Replace VALUE with the correct primary key
$action = str_replace ( "VALUE", $row [0], $actions );
$resultHTML .= "<td nowrap align=\"left\">$action</td>";
}
$resultHTML .= "</tr>";
}
$resultHTML .= "</table></td></tr></table>";
} else {
$resultHTML = "";
}
return $resultHTML;
}
/**
* method to retun the value of a given colum using one where clause
* #param $table
* #param $col
* #param $val1
* #param $col2
*/
function getRow($table, $col, $val1, $col2) {
$query = "SELECT '$col2' FROM " . $this->table_prefix . $table . " WHERE $col = '$val1'";
$this->query ( $query );
$resultArray = $this->fetchArray ();
return $resultArray [$col2];
}
/**
* method to test if a row conatining $x in the feild $y exists in the given $table
* method returns true or false
* #param $table
* #param $col
* #param $val
* #return boolian
*/
function rowExistsInDB($table, $col, $val) {
$this->query ( "SELECT $col FROM '" . $this->table_prefix . $table . "' WHERE '$col' = '$val'" );
if ($this->numRows () > 0) {
return true;
} else {
return false;
}
}
function rowExistsInDB2($table, $col, $val, $col2, $val2) {
$query = "SELECT " . $col . " FROM " . $this->table_prefix . $table . " WHERE " . $col . " = '" . mysqli_real_escape_string ( $val ) . "' AND " . $col2 . " = '" . mysqli_real_escape_string ( $val2 ) . "'";
$this->query ( $query );
if ($this->numRows () > 0) {
return true;
} else {
return false;
}
}
/**
* method to delete all rows where $col=$val in $table
* returns int of number of affected rows or false on fail
*
* #param string $table
* #param string $col
* #param string $val
* #return int
*/
function deleteRow($table, $col, $val) {
$this->query ( "DELETE FROM '" . $this->table_prefix . $table . "' WHERE '$col' = '$val'" );
return $this->result;
}
// Misc methods to do some convertions and stuff
// round or pad to 2 decimal points
function formatNum($num, $dec = 2) {
for($x = 0; $x <= 5; $x ++) {
$num = sprintf ( "%01." . ($dec + $x) . "f", $num );
return $num;
}
}
/**
* method to reverse the order of a given date
* and fix to mysql date format
* so DD/MM/YYYY becomes YYYY-MM-DD
*
* #param string $date
* #return string
*/
function revDate($date) {
// first split the date string # / int o three parts
$dateArray = explode ( '/', $date, 3 );
// then reorder them to YYY-MM-DD
$revDate = array_reverse ( $dateArray );
$i = 0;
foreach ( $revDate as $eliment ) {
$correctDate .= $eliment;
if ($i < 2) {
$correctDate .= "-";
}
$i ++;
}
return $correctDate;
}
/**
* method to revers dates taken from sql database
* so YYYY-MM-DD becomes DD/MM/YYYY
*
* #param string $date
* #return string
*/
function revSqlDate($date) {
// first split the date string # / int o three parts
$dateArray = explode ( '-', $date, 3 );
// then reorder them to DD/MM/YYYY
$revDate = array_reverse ( $dateArray );
$i = 0;
foreach ( $revDate as $eliment ) {
$correctDate .= $eliment;
if ($i < 2) {
$correctDate .= "/";
}
$i ++;
}
return $correctDate;
}
}
Write as:
config::$DBUSER;
and etc.

I can not resolve this error in SugarCRM

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;
}
}
?>

Categories