Below, there is my code for database backup.
$this->load->database();
$this->load->dbutil();
$backup =& $this->dbutil->backup();
$prefs = array(
'format' => 'txt',
'filename' => 'mybackup.sql', );
$path=$this->config->base_url()."database/";
$this->load->helper('file');
write_file($path, $backup);
$this->load->helper('download');
force_download('mybackup.gz', $backup);
It works fine when i use
$db['default']['dbdriver'] = 'mysql';
But it gives error with
$db['default']['dbdriver'] = 'mysqli';
error:Unsupported feature of the database platform you are using.
How it will work with "mysqli" i need support mysqli in my project.
This hapend to me, then i open file "system\database\drivers\mysqli\mysqli_utility.php" and change function "_backup" to this:
/**
* MySQLi Export
*
* #access private
* #param array Preferences
* #return mixed
*/
function _backup($params = array())
{
// Currently unsupported
//---return $this->db->display_error('db_unsuported_feature');
if (count($params) == 0)
{
return FALSE;
}
// Extract the prefs for simplicity
extract($params);
// Build the output
$output = '';
foreach ((array)$tables as $table)
{
// Is the table in the "ignore" list?
if (in_array($table, (array)$ignore, TRUE))
{
continue;
}
// Get the table schema
$query = $this->db->query("SHOW CREATE TABLE `".$this->db->database.'`.`'.$table.'`');
// No result means the table name was invalid
if ($query === FALSE)
{
continue;
}
// Write out the table schema
$output .= '#'.$newline.'# TABLE STRUCTURE FOR: '.$table.$newline.'#'.$newline.$newline;
if ($add_drop == TRUE)
{
$output .= 'DROP TABLE IF EXISTS '.$table.';'.$newline.$newline;
}
$i = 0;
$result = $query->result_array();
foreach ($result[0] as $val)
{
if ($i++ % 2)
{
$output .= $val.';'.$newline.$newline;
}
}
// If inserts are not needed we're done...
if ($add_insert == FALSE)
{
continue;
}
// Grab all the data from the current table
$query = $this->db->query("SELECT * FROM $table");
if ($query->num_rows() == 0)
{
continue;
}
// Fetch the field names and determine if the field is an
// integer type. We use this info to decide whether to
// surround the data with quotes or not
$i = 0;
$field_str = '';
$is_int = array();
while ($field = mysqli_fetch_field($query->result_id))
{
// Most versions of MySQL store timestamp as a string
$is_int[$i] = (in_array(
//strtolower(mysqli_field_type($query->result_id, $i)),
strtolower($field->type),
array('tinyint', 'smallint', 'mediumint', 'int', 'bigint'), //, 'timestamp'),
TRUE)
) ? TRUE : FALSE;
// Create a string of field names
$field_str .= '`'.$field->name.'`, ';
$i++;
}
// Trim off the end comma
$field_str = preg_replace( "/, $/" , "" , $field_str);
// Build the insert string
foreach ($query->result_array() as $row)
{
$val_str = '';
$i = 0;
foreach ($row as $v)
{
// Is the value NULL?
if ($v === NULL)
{
$val_str .= 'NULL';
}
else
{
// Escape the data if it's not an integer
if ($is_int[$i] == FALSE)
{
$val_str .= $this->db->escape($v);
}
else
{
$val_str .= $v;
}
}
// Append a comma
$val_str .= ', ';
$i++;
}
// Remove the comma at the end of the string
$val_str = preg_replace( "/, $/" , "" , $val_str);
// Build the INSERT string
$output .= 'INSERT INTO '.$table.' ('.$field_str.') VALUES ('.$val_str.');'.$newline;
}
$output .= $newline.$newline;
}
return $output;
}
If you need what change....
change all "mysql_..." to "mysqli..."
and the line
strtolower(mysqli_field_type($query->result_id, $i)),
To this
strtolower($field->type),
And viola! thats WORKS great...
Here is an extension to the function to backup all databases of any size.
This code will remove the PHP memory limits on exporting databases by utilising the file system (cache folder) and SQL LIMITS.
I hope this is useful to someone.
Replacement for function _backup($params = array())
FILE: system/drivers/mysqli/mysqli_utility.php
/**
* MySQLi Export
*
* #access private
* #param array Preferences
* #return mixed
*/
function _backup_old($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsuported_feature');
}
/**
* MySQLi Export
*
* #access private
* #param array Preferences
* #return mixed
*/
function _backup($params = array())
{
// Currently unsupported
//---return $this->db->display_error('db_unsuported_feature');
if (count($params) == 0)
{
return FALSE;
}
// Extract the prefs for simplicity
extract($params);
// Build the output
$output = '';
foreach ((array)$tables as $table)
{
// Temp file to reduce change of OOM Killer
$tempfilepath = APPPATH . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
$tempfile = $tempfilepath . 'dbbkp_tmp_' . time() . '.sql';
// Is the table in the "ignore" list?
if (in_array($table, (array)$ignore, TRUE))
{
continue;
}
// Get the table schema
$query = $this->db->query("SHOW CREATE TABLE `".$this->db->database.'`.`'.$table.'`');
// No result means the table name was invalid
if ($query === FALSE)
{
continue;
}
// Write out the table schema
$output .= '#'.$newline.'# TABLE STRUCTURE FOR: '.$table.$newline.'#'.$newline.$newline;
if ($add_drop == TRUE)
{
$output .= 'DROP TABLE IF EXISTS '.$table.';'.$newline.$newline;
}
$i = 0;
$result = $query->result_array();
foreach ($result[0] as $val)
{
if ($i++ % 2)
{
$output .= $val.';'.$newline.$newline;
}
}
// Write $output to the $filename file
file_put_contents( $filename, $output, LOCK_EX );
$output = '';
// If inserts are not needed we're done...
if ($add_insert == FALSE)
{
continue;
}
// Grab all the data from the current table
//$query = $this->db->query("SELECT * FROM $table"); // OLD
$countResult = $this->db->query("SELECT COUNT(*) AS `count` FROM " . $table . ";");
$countReturn = $countResult->result_array();
$totalCount = $countReturn[0]['count'];
//if ($query->num_rows() == 0) // OLD
if ($totalCount == 0)
{
continue;
}
// Chunk Vars
$chunkSize = 10000;
$from = 0;
$resultArray = array();
if (isset($chunk_size))
{
$chunkSize = $chunk_size;
}
// Write out the table schema
$output .= '#'.$newline.'# TABLE DATA FOR: '.$table.$newline.'#'.$newline.$newline;
// Write $output to the $filename file
file_put_contents( $filename, $output, FILE_APPEND | LOCK_EX );
// Fetch the field names and determine if the field is an
// integer type. We use this info to decide whether to
// surround the data with quotes or not
$query = $this->db->query("SELECT * FROM " . $table . " LIMIT 1;");
$i = 0;
$field_str = '';
$is_int = array();
while ($field = mysqli_fetch_field($query->result_id))
{
// Most versions of MySQL store timestamp as a string
$is_int[$i] = (in_array(
//strtolower(mysqli_field_type($query->result_id, $i)),
strtolower($field->type),
array('tinyint', 'smallint', 'mediumint', 'int', 'bigint'), //, 'timestamp'),
TRUE)
) ? TRUE : FALSE;
// Create a string of field names
$field_str .= '`'.$field->name.'`, ';
$i++;
}
// Trim off the end comma
$field_str = preg_replace( "/, $/" , "" , $field_str);
// Pull the data in chunks
while($from < $totalCount)
{
// empty $output
$output = '';
// Execute a limited query:
$dataChunkQuery = $this->db->query('SELECT * FROM ' . $table . ' LIMIT ' . $from . ', ' . $chunkSize . ';');
$dataChunkRows = $dataChunkQuery->result_array();
// Increase $from:
$from += $chunkSize;
// Build the insert string
//foreach ($query->result_array() as $row) // OLD
//var_dump($resultArray); die();
foreach ($dataChunkRows as $row)
{
$val_str = '';
$i = 0;
foreach ($row as $v)
{
// Is the value NULL?
if ($v === NULL)
{
$val_str .= 'NULL';
}
else
{
// Escape the data if it's not an integer
if ($is_int[$i] == FALSE)
{
$val_str .= $this->db->escape($v);
}
else
{
$val_str .= $v;
}
}
// Append a comma
$val_str .= ', ';
$i++;
}
// Remove the comma at the end of the string
$val_str = preg_replace( "/, $/" , "" , $val_str);
// Build the INSERT string
$output .= 'INSERT INTO '.$table.' ('.$field_str.') VALUES ('.$val_str.');'.$newline;
}
// Write $output to the $filename file
file_put_contents( $filename, $output, FILE_APPEND | LOCK_EX );
sleep(1); // used to help reduce the CPU load
}
}
if( file_exists($filename) ) {
return true;
} else {
return false;
}
}
CI Model built for DB Backups
FILE: models/databasebackup_model.php
<?php
/**
* Database Backup
* - Used to make backups of the database system
* #author Adan Rehtla <adan.rehtla#aamcommercial.com.au>
*/
class Databasebackup_model extends API_Model {
private $CI;
private $lpFilePath = APPPATH . 'cache/backup/';
// Tables to ignore when doing a backup
private $laIgnoreTables = array(
'ci_sessions',
'any_other_tables_to_ignore'
);
/**
* Constructor
* #author Adan Rehtla <adan.rehtla#aamcommercial.com.au>
*/
function __construct() {
parent::__construct();
$this->CI = &get_instance();
}
/**
* Check and empty the cache location for storing the backups during transit
* #author Adan Rehtla <adan.rehtla#aamcommercial.com.au>
* #return json Result
*/
public function check_cache() {
$arrRet = false;
if( ! file_exists( $this->lpFilePath ) ) {
$arrRet = mkdir( $this->lpFilePath );
$arrRet = true;
}
$files = glob( $this->lpFilePath . '*' ); // get all file names present in folder
foreach( $files as $file ){ // iterate files
if( is_file( $file ) ) unlink( $file ); // delete the file
}
return (object) $arrRet;
}
/**
* Build a list of tables to backup
* #author Adan Rehtla <adan.rehtla#aamcommercial.com.au>
* #return json Result
*/
public function find_tables() {
$arrRet = false;
if( $this->database('db_read') ) {
$this->db_read->_protect_identifiers = FALSE;
$this->db_read->start_cache();
$this->db_read->distinct();
$this->db_read->select("table_name");
$this->db_read->from("information_schema.columns");
$this->db_read->where("table_schema", $this->db->dbprefix . $this->db->database);
$this->db_read->stop_cache();
// Get List of all tables to backup
$laTableNameResult = $this->db_read->get()->result();
$this->db_read->flush_cache();
if( !empty($laTableNameResult) ) {
foreach($laTableNameResult as $loTableName) {
if( ! in_array( $loTableName->table_name, $this->laIgnoreTables ) ) {
$arrRet[] = $loTableName->table_name;
}
}
}
$this->db_read->_protect_identifiers = TRUE;
}
return (object) $arrRet;
}
/**
* Backup the database to Amazon S3
* #author Adan Rehtla <adan.rehtla#aamcommercial.com.au>
* #param interger $lpUserId Logged in User ID
* #return json Result
*/
public function backup() {
ini_set('max_execution_time', 3600); // 3600 seconds = 60 minutes
ini_set('memory_limit', '-1'); // unlimited memory
//error_reporting(E_ALL); // show errors
//ini_set('display_errors', 1); // display errors
$arrRet = array();
$lpBackupCount = 0;
$zipNumFiles = 0;
$zipStatus = 0;
if( $this->database('db_read') ) {
$this->db->save_queries = false;
$this->load->dbutil( $this->db_read, TRUE );
$laBackupTables = $this->find_tables();
if( !empty($laBackupTables) && $this->check_cache() ) {
foreach($laBackupTables as $lpTableName) {
$lpFilename = $this->lpFilePath . 'backup-' . $lpTableName . '-' . date('Ymd-His') . '.sql';
$prefs = array(
'tables' => $lpTableName,
'format' => 'sql',
'filename' => $lpFilename,
'add_drop' => TRUE,
'add_insert' => TRUE,
'newline' => "\n",
'foreign_key_checks' => TRUE,
'chunk_size' => 1000
);
if( !file_exists( $lpFilename ) ){
if( $this->dbutil->backup( $prefs ) ) {
$lpBackupCount++;
}
}
sleep(1); // used to help reduce the CPU load
//break; // used to debug and testing to only process the first database table
}
try {
// ZIP up all the individual GZIPs
$zip = new ZipArchive();
$zip_file = $this->lpFilePath . '-' . date('Ymd-His') . '.zip';
$zip_files = glob( $this->lpFilePath . 'backup-*' ); // get all file names present in folder starting with 'backup-'
if( $zip->open( $zip_file, ZIPARCHIVE::CREATE ) !== TRUE ) {
exit("cannot open <$zip_file>\n");
}
if( !empty($zip_files) ) {
foreach( $zip_files as $file_to_zip ) { // iterate files
$zip->addFile( $file_to_zip, basename( $file_to_zip ) );
}
}
$zipNumFiles = $zip->numFiles;
$zipStatus = $zip->status;
$zip->close();
} catch (Vi_exception $e) {
print( strip_tags( $e->errorMessage() ) );
}
// Upload the file to Amazon S3
// REMOVED AWS S3 UPLOAD CODE
// REMOVED AWS S3 UPLOAD CODE
// REMOVED AWS S3 UPLOAD CODE
// Clean up cache files
$this->check_cache();
}
$this->db->save_queries = true;
}
if( !empty($lpBackupCount) && !empty($zip) && !empty($zip_file) ) {
return (object) array( 'success'=>true, 'totalTables'=>$lpBackupCount, 'zipNumFiles'=>$zipNumFiles, 'zipStatus'=>$zipStatus, 'zipFile'=>$zip_file );
} else {
return (object) array( 'success'=>false );
}
}
}
USAGE:
$this->load->model('databasebackup_model');
$laResult = $this->databasebackup_model->backup();
Your mysqli driver does n't support this feature.
Refer this:
http://ellislab.com/forums/viewthread/194645/#979255
Related
I'm getting a PHP fatal error on a cron script used for Commission Junction. It seems in the error_log it keeps updating with
PHP Fatal error: Call to undefined method Mage_Core_Helper_Data::getEscapedCSVData() in /home/lovescen/public_html/app/code/core/Mage/Dataflow/Model/Convert/Parser/Csv.php on line 269
The code on line 269 is
$escapedValue = Mage::helper("core")->getEscapedCSVData(array($value));
And here is the entire code in Csv.php.
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* #category Mage
* #package Mage_Dataflow
* #copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Convert csv parser
*
* #category Mage
* #package Mage_Dataflow
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_Dataflow_Model_Convert_Parser_Csv extends Mage_Dataflow_Model_Convert_Parser_Abstract
{
protected $_fields;
protected $_mapfields = array();
public function parse()
{
// fixed for multibyte characters
setlocale(LC_ALL, Mage::app()->getLocale()->getLocaleCode().'.UTF-8');
$fDel = $this->getVar('delimiter', ',');
$fEnc = $this->getVar('enclose', '"');
if ($fDel == '\t') {
$fDel = "\t";
}
$adapterName = $this->getVar('adapter', null);
$adapterMethod = $this->getVar('method', 'saveRow');
if (!$adapterName || !$adapterMethod) {
$message = Mage::helper('dataflow')->__('Please declare "adapter" and "method" nodes first.');
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
try {
$adapter = Mage::getModel($adapterName);
}
catch (Exception $e) {
$message = Mage::helper('dataflow')->__('Declared adapter %s was not found.', $adapterName);
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
if (!method_exists($adapter, $adapterMethod)) {
$message = Mage::helper('dataflow')->__('Method "%s" not defined in adapter %s.', $adapterMethod, $adapterName);
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
$batchModel = $this->getBatchModel();
$batchIoAdapter = $this->getBatchModel()->getIoAdapter();
if (Mage::app()->getRequest()->getParam('files')) {
$file = Mage::app()->getConfig()->getTempVarDir().'/import/'
. urldecode(Mage::app()->getRequest()->getParam('files'));
$this->_copy($file);
}
$batchIoAdapter->open(false);
$isFieldNames = $this->getVar('fieldnames', '') == 'true' ? true : false;
if (!$isFieldNames && is_array($this->getVar('map'))) {
$fieldNames = $this->getVar('map');
}
else {
$fieldNames = array();
foreach ($batchIoAdapter->read(true, $fDel, $fEnc) as $v) {
$fieldNames[$v] = $v;
}
}
$countRows = 0;
while (($csvData = $batchIoAdapter->read(true, $fDel, $fEnc)) !== false) {
if (count($csvData) == 1 && $csvData[0] === null) {
continue;
}
$itemData = array();
$countRows ++; $i = 0;
foreach ($fieldNames as $field) {
$itemData[$field] = isset($csvData[$i]) ? $csvData[$i] : null;
$i ++;
}
$batchImportModel = $this->getBatchImportModel()
->setId(null)
->setBatchId($this->getBatchModel()->getId())
->setBatchData($itemData)
->setStatus(1)
->save();
}
$this->addException(Mage::helper('dataflow')->__('Found %d rows.', $countRows));
$this->addException(Mage::helper('dataflow')->__('Starting %s :: %s', $adapterName, $adapterMethod));
$batchModel->setParams($this->getVars())
->setAdapter($adapterName)
->save();
//$adapter->$adapterMethod();
return $this;
// // fix for field mapping
// if ($mapfields = $this->getProfile()->getDataflowProfile()) {
// $this->_mapfields = array_values($mapfields['gui_data']['map'][$mapfields['entity_type']]['db']);
// } // end
//
// if (!$this->getVar('fieldnames') && !$this->_mapfields) {
// $this->addException('Please define field mapping', Mage_Dataflow_Model_Convert_Exception::FATAL);
// return;
// }
//
// if ($this->getVar('adapter') && $this->getVar('method')) {
// $adapter = Mage::getModel($this->getVar('adapter'));
// }
//
// $i = 0;
// while (($line = fgetcsv($fh, null, $fDel, $fEnc)) !== FALSE) {
// $row = $this->parseRow($i, $line);
//
// if (!$this->getVar('fieldnames') && $i == 0 && $row) {
// $i = 1;
// }
//
// if ($row) {
// $loadMethod = $this->getVar('method');
// $adapter->$loadMethod(compact('i', 'row'));
// }
// $i++;
// }
//
// return $this;
}
public function parseRow($i, $line)
{
if (sizeof($line) == 1) return false;
if (0==$i) {
if ($this->getVar('fieldnames')) {
$this->_fields = $line;
return;
} else {
foreach ($line as $j=>$f) {
$this->_fields[$j] = $this->_mapfields[$j];
}
}
}
$resultRow = array();
foreach ($this->_fields as $j=>$f) {
$resultRow[$f] = isset($line[$j]) ? $line[$j] : '';
}
return $resultRow;
}
/**
* Read data collection and write to temporary file
*
* #return Mage_Dataflow_Model_Convert_Parser_Csv
*/
public function unparse()
{
$batchExport = $this->getBatchExportModel()
->setBatchId($this->getBatchModel()->getId());
$fieldList = $this->getBatchModel()->getFieldList();
$batchExportIds = $batchExport->getIdCollection();
$io = $this->getBatchModel()->getIoAdapter();
$io->open();
if (!$batchExportIds) {
$io->write("");
$io->close();
return $this;
}
if ($this->getVar('fieldnames')) {
$csvData = $this->getCsvString($fieldList);
$io->write($csvData);
}
foreach ($batchExportIds as $batchExportId) {
$csvData = array();
$batchExport->load($batchExportId);
$row = $batchExport->getBatchData();
foreach ($fieldList as $field) {
$csvData[] = isset($row[$field]) ? $row[$field] : '';
}
$csvData = $this->getCsvString($csvData);
$io->write($csvData);
}
$io->close();
return $this;
}
public function unparseRow($args)
{
$i = $args['i'];
$row = $args['row'];
$fDel = $this->getVar('delimiter', ',');
$fEnc = $this->getVar('enclose', '"');
$fEsc = $this->getVar('escape', '\\');
$lDel = "\r\n";
if ($fDel == '\t') {
$fDel = "\t";
}
$line = array();
foreach ($this->_fields as $f) {
$v = isset($row[$f]) ? str_replace(array('"', '\\'), array($fEnc.'"', $fEsc.'\\'), $row[$f]) : '';
$line[] = $fEnc.$v.$fEnc;
}
return join($fDel, $line);
}
/**
* Retrieve csv string from array
*
* #param array $fields
* #return string
*/
public function getCsvString($fields = array()) {
$delimiter = $this->getVar('delimiter', ',');
$enclosure = $this->getVar('enclose', '');
$escapeChar = $this->getVar('escape', '\\');
if ($delimiter == '\t') {
$delimiter = "\t";
}
$str = '';
foreach ($fields as $value) {
$escapedValue = Mage::helper("core")->getEscapedCSVData(array($value));
$value = $escapedValue[0];
if (strpos($value, $delimiter) !== false ||
empty($enclosure) ||
strpos($value, $enclosure) !== false ||
strpos($value, "\n") !== false ||
strpos($value, "\r") !== false ||
strpos($value, "\t") !== false ||
strpos($value, ' ') !== false) {
$str2 = $enclosure;
$escaped = 0;
$len = strlen($value);
for ($i=0;$i<$len;$i++) {
if ($value[$i] == $escapeChar) {
$escaped = 1;
} else if (!$escaped && $value[$i] == $enclosure) {
$str2 .= $enclosure;
} else {
$escaped = 0;
}
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2.$delimiter;
} else {
$str .= $enclosure.$value.$enclosure.$delimiter;
}
}
return substr($str, 0, -1) . "\n";
}
}
Not sure how to fix this problem. If I could get some help I'd really appreciate it.
Thanks
UPDATE
Here is the code from my app/code/core/Mage/Core/Helper/Data.php file: http://pastie.org/10815259
Does the file app/code/core/Mage/Core/Helper/Data.php have the getEscapedCSVData function in it?
It appears that this function is added by SUPEE-7405. Have you patched your store with this SUPEE?
In my case some previous programer have copy the file
from core
\app\code\core\Mage\Core\Helper\Data.php
to local
app\code\local\Mage\Core\Helper\Data.php
and then apply SUPE PATCH 7405...
it cause that all modifications made by SUPE in data.php where rewrite by the old ones in local folder...
Solution: copy the new data.php to local or made a extension of class (better solution)
What is the problem to the code? I cannot upload to database. It comes the message:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ACQUA'))' at line 2
query was:
SELECT `vals`.*, `opt`.*
FROM `eav_attribute_option_value` AS `vals`
INNER JOIN `eav_attribute_option` AS `opt` ON opt.option_id = vals.option_id
WHERE (opt.attribute_id='191')
AND (vals.value in ('ALESSANDRO DELL'ACQUA'))
PHP Code:
<?php
/**
* Adapted by Christopher Shennan
* http://www.chrisshennan.com
*
* Date: 20/04/2011
*
* Adaptered from original post by Srinigenie
* Original Post - http://www.magentocommerce.com/boards/viewthread/9391/
*/
class Mage_Eav_Model_Import extends Mage_Eav_Model_Mysql4_Entity_Attribute {
private $fileName;
private $delimiter = '|';
private $enclosure = '"';
private function &getCsv() {
$file = fopen($this->fileName, "r");
while (!feof($file)) {
$csvArr[] = fgetcsv($file, 0, $this->delimiter, $this->enclosure);
}
fclose($file);
return $csvArr;
}
protected function populateOptionTable($attribId) {
echo "Upload Begin<br/>";
$fields = array();
$values = array(); // store id => values
$optionValues = array(); // option id => $values
$option = array('value' => $optionValues);
$updateOptionValId;
$values = null;
$row = null;
$disCounter = 0;
$optionTable = $this->getTable('attribute_option');
$optionValueTable = $this->getTable('attribute_option_value');
$write = $this->_getWriteAdapter();
$csvStoreArr = array();
// Get CSV into Array
$csv = & $this->getCsv();
$read = $this->_getReadAdapter();
// exit if the csv file is empty or if it contains only the headers
if (count($csv) < 1 or count($csv) == 1)
return;
$fields = $csv[0]; // get the field headers from first row of CSV
// get the store Ids
$stores = Mage::getModel('core/store')
->getResourceCollection()
->setLoadDefault(true)
->load();
// determine the stores for which option values are being uploaded for
foreach ($fields as $hdr) {
if ($hdr === 'position' || $hdr === 'isDefault' || $hdr === 'ERROR') {
continue;
}
foreach ($stores as $store) {
if ($store->getCode() === $hdr)
$csvStoreArr[$hdr] = $store->getId();
}
}
// start reading the option values - from row 1 (note that 0 represents headers)
for ($indx = 1; $indx < count($csv); $indx++) {
$values = null; // initialize to null
$row = $csv[$indx]; // get row
if (isset($row) && count($row) > 0) {
//escape the single quote
//$whereParam = $read->quote($row);
if (is_array($row))
$whereParam = '(\'' . implode($row, '\',\'') . '\')';
else if (strlen($row))
$whereParam = '(\'' . $row . '\')';
$select = $read->select()->from(array('vals' => $optionValueTable))
->join(array('opt' => $optionTable), 'opt.option_id=vals.option_id')
->where('opt.attribute_id=?', $attribId);
$select = $select
->where('vals.value in ' . $whereParam);
$optionValData = $read->fetchAll($select);
unset($select);
// get the option Id for this option
if (count($optionValData) > 0) {
$optionValDataRow = $optionValData[0];
$optionId = $optionValDataRow['option_id'];
} else
$optionId = null;
$intOptionId = (int) $optionId;
if (!$intOptionId) {
$data = array(
'attribute_id' => $attribId,
'sort_order' => isset($option['order'][$optionId]) ? $option['order'][$optionId] : 0,
);
try {
$write->insert($optionTable, $data);
$intOptionId = $write->lastInsertId();
} catch (Exception $e) {
Mage::log($e->getMessage());
}
} else {
$data = array(
'sort_order' => isset($option['order'][$optionId]) ? $option['order'][$optionId] : 0,
);
$write->update($optionTable, $data, $write->quoteInto('option_id=?', $intOptionId));
}
$colIndx = 0; //initialize row's column index
if (isset($row) && is_array($row) && count($row) > 0) {
foreach ($row as $optVal) {
if ($fields[$colIndx] !== 'position' || $fields[$colIndx] !== 'isDefault' || $fields[$colIndx] !== 'ERROR') {
$values[$csvStoreArr[$fields[$colIndx]]] = $optVal; // store id => option value
}
$colIndx++;
}
}
}
if (isset($values) && is_array($values) && count($values) > 0) {
foreach ($values as $storeId => $value) {
if (!empty($value) || strlen($value) > 0) {
$value = trim($value);
$data = array(
'option_id' => $intOptionId,
'store_id' => $storeId,
'value' => $value,
);
$optionValInsert = true;
$optionValUpdate = false;
foreach ($optionValData as $valData) {
if ((int) $valData['option_id'] === $intOptionId &&
(int) $valData['store_id'] === $storeId) {
$optionValInsert = false;
if (strcasecmp(trim($valData['value']), $value) !== 0) {
$optionValUpdate = true;
$updateOptionValId = $valData['value_id'];
}
break;
}
}
if ($optionValInsert) {
$write->insert($optionValueTable, $data);
Mage::log('Inserted Value -' . $value);
} else if ($optionValUpdate) {
$write->update($optionValueTable, $data, $write->quoteInto('option_id=?', $updateOptionValId));
Mage::log('Updated Value -' . $value);
}
}
}
}
$optionValues[$optionId] = $values;
if ($indx % 20 == 0) {
echo "" . $indx . ' - uploaded!!<br />';
Mage::log($indx . ' - attributes uploaded!!', null, $this->fileName . '.log');
}
}
echo "" . $indx . ' - uploaded!!<br />';
echo '<b> Attribute Upload Finished </b><br />';
$option['value'] = $optionValues;
return null;
}
/**
* Enter description here...
*
* #param Mage_Core_Model_Abstract $object
* #return Mage_Eav_Model_Mysql4_Entity_Attribute
*/
public function saveOptionValues($attributeId, $fn) {
$option = array();
$this->fileName = $fn;
echo '<strong>Importing Attributes</strong><br/><br/>Reading file contents - ' . $this->fileName . '<br />';
Mage::log("Upload Begin", null, $this->fileName . '.log');
// Step 1 -- Get attribute Id from attribute code
$atrribId = $attributeId; //569
// Step 2 Obtain the option values into an array
$option = $this->populateOptionTable($atrribId);
}
}
Error is because of single Quotes in the string : 'ALESSANDRO DELL'ACQUA.
SELECT vals., opt. FROM eav_attribute_option_value AS vals INNER JOIN
eav_attribute_option AS opt ON opt.option_id=vals.option_id WHERE
(opt.attribute_id='191') AND (vals.value in ('ALESSANDRO
DELL'ACQUA'))
Try using double quotes.
String Literals in MySQL [ https://dev.mysql.com/doc/refman/5.0/en/string-literals.html ]
' single quote is reserved character in MySQL and there are several ways to include quote characters within a string:
A "'" inside a string quoted with "'" may be written as ""''".
A """ inside a string quoted with """ may be written as """".
Precede the quote character by an escape character (""\").
A "'" inside a string quoted with """ needs no special treatment and
need not be doubled or escaped. In the same way, """ inside a string
quoted with "'" needs no special treatment.
To avoid this use PreparedStatement in PHP http://www.w3schools.com/php/php_mysql_prepared_statements.asp
In your query is should be like 'ALESSANDRO DELL''ACQUA' instead of 'ALESSANDRO DELL'ACQUA'
I have found a php inventory http://inventory-management.org/ easy but was written in PHP4? and I run now on PHP5. I have found some errors that I have already managed to fix but they are keep coming up so I would like to see if I can managed to run at the end. (As it is really simple script only has 5-7 php files).
Could someone help me please how to fix this error?
Fatal error: Cannot redeclare fputcsv() in C:\xampp\htdocs\Inventory\lib\common.php on line 935
which is:
function fputcsv ($fp, $array, $deliminator=",") {
return fputs($fp, putcsv($array,$delimitator));
}#end fputcsv()
here is the full code:
<?php
/*
*/
/**
* description returns an array with filename base name and the extension
*
* #param filemane format
*
* #return array
*
* #access public
*/
function FileExt($filename) {
//checking if the file have an extension
if (!strstr($filename, "."))
return array("0"=>$filename,"1"=>"");
//peoceed to normal detection
$filename = strrev($filename);
$extpos = strpos($filename , ".");
$file = strrev(substr($filename , $extpos + 1));
$ext = strrev(substr($filename , 0 , $extpos));
return array("0"=>$file,"1"=>$ext);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function UploadFile($source, $destination , $name ="") {
$name = $name ? $name : basename($source);
$name = FileExt($name);
$name[2]= $name[0];
$counter = 0 ;
while (file_exists( $destination . $name[0] . "." . $name[1] )) {
$name[0] = $name[2] . $counter;
$counter ++;
}
copy($source , $destination . $name[0] . "." . $name[1] );
#chmod($destination . $name[0] . "." . $name[1] , 0777);
}
function UploadFileFromWeb($source, $destination , $name) {
$name = FileExt($name);
$name[2]= $name[0];
$counter = 0 ;
while (file_exists( $destination . $name[0] . "." . $name[1] )) {
$name[0] = $name[2] . $counter;
$counter ++;
}
SaveFileContents($destination . $name[0] . "." . $name[1] , $source);
#chmod($destination . $name[0] . "." . $name[1] , 0777);
}
/**
* returns the contents of a file in a string
*
* #param string $file_name name of file to be loaded
*
* #return string
*
* #acces public
*/
function GetFileContents($file_name) {
// if (!file_exists($file_name)) {
// return null;
// }
//echo "<br>:" . $file_name;
$file = fopen($file_name,"r");
//checking if the file was succesfuly opened
if (!$file)
return null;
if (strstr($file_name,"://"))
while (!feof($file))
$result .= fread($file,1024);
else
$result = #fread($file,filesize($file_name));
fclose($file);
return $result;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function SaveFileContents($file_name,$content) {
// echo $file_name;
$file = fopen($file_name,"w");
fwrite($file,$content);
fclose($file);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Debug($what,$pre = 1,$die = 0) {
if (PB_DEBUG_EXT == 1) {
if ($pre == 1)
echo "<pre style=\"background-color:white;\">";
print_r($what);
if ($pre == 1)
echo "</pre>";
if ($die == 1)
die;
}
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function SendMail($to,$from,$subject,$message,$to_name,$from_name) {
if ($to_name)
$to = "$to_name <$to>";
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text; charset=iso-8859-1\n";
if ($from_name) {
$headers .= "From: $from_name <$from>\n";
$headers .= "Reply-To: $from_name <$from>\n";
}
else {
$headers .= "From: $from\n";
$headers .= "Reply-To: $from\n";
}
$headers .= "X-Mailer: PHP/" . phpversion();
return mail($to, $subject, $message,$headers);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function FillVars($var,$fields,$with) {
$fields = explode (",",$fields);
foreach ($fields as $field)
if (!$var[$field])
!$var[$field] = $with;
return $var;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CleanupString($string,$strip_tags = TRUE) {
$string = addslashes(trim($string));
if ($strip_tags)
$string = strip_tags($string);
return $string;
}
define("RX_EMAIL","^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$");
define("RX_CHARS","[a-z\ ]");
define("RX_DIGITS","[0-9]");
define("RX_ALPHA","[^a-z0-9_]");
define("RX_ZIP","[0-9\-]");
define("RX_PHONE","[0-9\-\+\(\)]");
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CheckString($string,$min,$max,$regexp = "",$rx_result = FALSE) {
if (get_magic_quotes_gpc() == 0)
$string = CleanupString($string);
if (strlen($string) < $min)
return 1;
elseif (($max != 0) && (strlen($string) > $max))
return 2;
elseif ($regexp != "")
if ($rx_result == eregi($regexp,$string))
return 3;
return 0;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/// FIRST_NAME:S:3:60,LAST_NAME:S...
function ValidateVars($source,$vars) {
$vars = explode(",",$vars);
foreach ($vars as $var) {
list($name,$type,$min,$max) = explode(":",$var);
switch ($type) {
case "S":
$type = RX_CHARS;
$rx_result = FALSE;
break;
case "I":
$type = RX_DIGITS;
$rx_result = TRUE;
break;
case "E":
$type = RX_EMAIL;
$rx_result = FALSE;
break;
case "P":
$type = RX_PHONE;
$rx_result = TRUE;
break;
case "Z":
$type = RX_ZIP;
$rx_result = FALSE;
break;
case "A":
$type = "";
break;
case "F":
//experimental crap
$type = RX_ALPHA;
$rx_result = TRUE;
//$source[strtolower($name)] = str_replace(" ", "" , $source[strtolower($name)] );
break;
}
//var_dump($result);
if (($result = CheckString($source[strtolower($name)],$min,$max,$type,$rx_result)) != 0)
$errors[] = $name;
}
return is_array($errors) ? $errors : 0;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ResizeImage($source,$destination,$size) {
if (PB_IMAGE_MAGICK == 1)
system( PB_IMAGE_MAGICK_PATH . "convert $source -resize {$size}x{$size} $destination");
else
copy($source,$destination);
}
/**
* uses microtime() to return the current unix time w/ microseconds
*
* #return float the current unix time in the form of seconds.microseconds
*
* #access public
*/
function GetMicroTime() {
list($usec,$sec) = explode(" ",microtime());
return (float) $usec + (float) $sec;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetArrayPart($input,$from,$count) {
$return = array();
$max = count($input);
for ($i = $from; $i < $from + $count; $i++ )
if ($i<$max)
$return[] = $input[$i];
return $return;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ReplaceAllImagesPath($htmldata,$image_path) {
$htmldata = stripslashes($htmldata);
// replacing IE formating style
$htmldata = str_replace("<IMG","<img",$htmldata);
// esmth, i dont know why i'm doing
preg_match_all("'<img.*?>'si",$htmldata,$images);
//<?//ing edit plus
foreach ($images[0] as $image)
$htmldata = str_replace($image,ReplaceImagePath($image,$image_path),$htmldata);
return $htmldata;//implode("\n",$html_out);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ReplaceImagePath($image,$replace) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
//getting only image name
$image_arr[$i][1] = strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/")));
// building the image back
$image_arr[$i][1] = "\"" . $replace . $image_arr[$i][1] . "\"";
$image_arr[$i] = implode ("=",$image_arr[$i]);
}
}
// adding tags
return "<" . implode(" ",$image_arr) . ">";
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function DowloadAllImages($images,$path) {
foreach ($images as $image)
#SaveFileContents($path ."/".ExtractFileNameFromPath($image),#implode("",#file($image)));
}
function GetAllImagesPath($htmldata) {
$htmldata = stripslashes($htmldata);
// replacing IE formating style
$htmldata = str_replace("<IMG","<img",$htmldata);
// esmth, i dont know why i'm doing
preg_match_all("'<img.*?>'si",$htmldata,$images);
//<?//ing edit plus
foreach ($images[0] as $image)
$images_path[] = GetImageName($image);
return $images_path;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetImagePath($image) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
return strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/")));;
}
}
// adding tags
return "";
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetImageName($image) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
return $image_arr[$i][1];
}
}
// adding tags
return "";
}
/**
* reinventing the wheel [badly]
*
* #param somthin
*
* #return erroneous
*
* #access denied
*/
function ExtractFileNameFromPath($file) {
//return strrev(substr(strrev($file),0,strpos(strrev($file),"/")));
// sau ai putea face asha. umpic mai smart ca mai sus dar tot stupid
// daca le dai path fara slashes i.e. un filename prima returneaza "" asta taie primu char
//return substr($file,strrpos($file,"/") + 1,strlen($file) - strrpos($file,"/"));
// corect ar fi cred asha [observa smart usage`u de strRpos]
//return substr($file,strrpos($file,"/") + (strstr($file,"/") ? 1 : 0),strlen($file) - strrpos($file,"/"));
// sau putem folosi tactica `nute mai caca pe tine and rtm' shi facem asha
return basename($file);
// har har :]]
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function RemoveArraySlashes($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = RemoveArraySlashes($item);
else
$array[$key] = stripslashes($item);
return $array;
}
function AddArraySlashes($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = AddArraySlashes($item);
else
$array[$key] = addslashes($item);
return $array;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Ahtmlentities($array) {
if (is_array($array))
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ahtmlentities($item);
else
$array[$key] = htmlentities(stripslashes($item),ENT_COMPAT);
else
return htmlentities(stripslashes($array),ENT_COMPAT);
return $array;
}
function AStripSlasshes($array) {
if (is_array($array))
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = AStripSlasshes($item);
else
$array[$key] = stripslashes($item);
else
return stripslashes($array);
return $array;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Ahtml_entity_decode($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ahtml_entity_decode($item);
else
$array[$key] = html_entity_decode($item,ENT_COMPAT);
return $array;
}
function array2xml ($name, $value, $indent = 1)
{
$indentstring = "\t";
for ($i = 0; $i < $indent; $i++)
{
$indentstring .= $indentstring;
}
if (!is_array($value))
{
$xml = $indentstring.'<'.$name.'>'.$value.'</'.$name.'>'."\n";
}
else
{
if($indent === 1)
{
$isindex = False;
}
else
{
$isindex = True;
while (list ($idxkey, $idxval) = each ($value))
{
if ($idxkey !== (int)$idxkey)
{
$isindex = False;
}
}
}
reset($value);
while (list ($key, $val) = each ($value))
{
if($indent === 1)
{
$keyname = $name;
$nextkey = $key;
}
elseif($isindex)
{
$keyname = $name;
$nextkey = $name;
}
else
{
$keyname = $key;
$nextkey = $key;
}
if (is_array($val))
{
$xml .= $indentstring.'<'.$keyname.'>'."\n";
$xml .= array2xml ($nextkey, $val, $indent+1);
$xml .= $indentstring.'</'.$keyname.'>'."\n";
}
else
{
$xml .= array2xml ($nextkey, $val, $indent);
}
}
}
return $xml;
}
function GetPhpContent($file) {
if (file_exists($file) ) {
$data = GetFileContents($file);
//replacing special chars in content
$data = str_replace("<?php","",$data);
$data = str_replace("?>","",$data);
return $data;
}
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function KeyArray($array,$recurse = 0 , $count = 1) {
if (is_array($array)) {
foreach ($array as $key => $val) {
$array[$key]["key"] = $count ++;
if ($recurse) {
foreach ($array[$key] as $k => $val)
if (is_array($val)) {
KeyArray($array[$key][$k] , $recurse , $count);
}
}
}
}
return $count + 1;
}
function RandomWord( $passwordLength ) {
$password = "";
for ($index = 1; $index <= $passwordLength; $index++) {
// Pick random number between 1 and 62
$randomNumber = rand(1, 62);
// Select random character based on mapping.
if ($randomNumber < 11)
$password .= Chr($randomNumber + 48 - 1); // [ 1,10] => [0,9]
else if ($randomNumber < 37)
$password .= Chr($randomNumber + 65 - 10); // [11,36] => [A,Z]
else
$password .= Chr($randomNumber + 97 - 36); // [37,62] => [a,z]
}
return $password;
}
function DeleteFolder($file) {
if (file_exists($file)) {
chmod($file,0777);
if (is_dir($file)) {
$handle = opendir($file);
while($filename = readdir($handle)) {
if ($filename != "." && $filename != "..") {
DeleteFolder($file."/".$filename);
}
}
closedir($handle);
rmdir($file);
} else {
unlink($file);
}
}
}
function GenerateRecordID($array) {
$max = 0;
if (is_array($array)) {
foreach ($array as $key => $val)
$max = ($key > $max ? $key : $max);
return $max + 1;
}
else return 1;
}
/*****************************************************
Links cripting for admin
DO NOT TOUCH UNLKESS YOU KNOW WHAT YOU ARE DOING
*****************************************************/
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CryptLink($link) {
if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1)) {
if (stristr($link,"javascript:")) {
/* if (stristr($link,"window.location=")) {
$pos = strpos($link , "window.location=");
$js = substr($link , 0 , $pos + 17 );
$final = substr($link , $pos + 17 );
$final = substr($final, 0, strlen($final) - 1 );
//well done ... crypt the link now
$url = #explode("?" , $final);
if (!is_array($url))
$url[0] = $final;
$tmp = str_replace( $url[0] . "?" , "" , $final);
$uri = urlencode(urlencode(base64_encode(str_rot13($tmp))));
$link = $js . $url[0] . "?" . $uri . md5($uri) . "'";
}
*/
} else {
$url = #explode("?" , $link);
if (!is_array($url))
$url[0] = $link;
$tmp = str_replace( $url[0] . "?" , "" , $link);
$uri = urlencode(urlencode(base64_encode(str_rot13($tmp))));
$link = $url[0] . "?" . $uri . md5($uri);
}
}
return $link;
}
/************************************************************************/
/* SOME PREINITIALISATION CRAP*/
if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1) ) {
$key = key($_GET);
if (is_array($_GET) && (count($_GET) == 1) && ($_GET[$key] == "")) {
$tmp = $_SERVER["QUERY_STRING"];
//do the md5 check
$md5 = substr($tmp , -32);
$tmp = substr($tmp , 0 , strlen($tmp) - 32);
if ($md5 != md5($tmp)) {
//header("index.php?action=badrequest");
//exit;
die("Please dont change the links!");
}
$tmp = str_rot13(base64_decode(urldecode(urldecode($tmp))));
$tmp_array = #explode("&" , $tmp);
$tmp_array = is_array($tmp_array) ? $tmp_array : array($tmp);
if (is_array($tmp_array)) {
foreach ($tmp_array as $key => $val) {
$tmp2 = explode("=" , $val);
$out[$tmp2[0]] = $tmp2[1];
}
} else {
$tmp2 = explode("=" , $tmp);
$out[$tmp2[0]] = $tmp2[1];
}
$_GET = $out;
}
}
/***********************************************************************/
function ArrayReplace($what , $with , $array ) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ArrayReplace($what , $with , $item);
else
$array[$key] = str_replace($what , $with , $item);
return $array;
}
function stri_replace( $find, $replace, $string )
{
$parts = explode( strtolower($find), strtolower($string) );
$pos = 0;
foreach( $parts as $key=>$part ){
$parts[ $key ] = substr($string, $pos, strlen($part));
$pos += strlen($part) + strlen($find);
}
return( join( $replace, $parts ) );
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GMTDate($format , $date) {
global $_GMT;
return date($format , $date - $_GMT);
}
function putcsv ($array, $deliminator=",") {
$line = "";
foreach($array as $val) {
# remove any windows new lines,
# as they interfere with the parsing at the other end
$val = str_replace("\r\n", "\n", $val);
# if a deliminator char, a double quote char or a newline
# are in the field, add quotes
if(ereg("[$deliminator\"\n\r]", $val)) {
$val = '"'.str_replace('"', '""', $val).'"';
}#end if
$line .= $val.$deliminator;
}#end foreach
# strip the last deliminator
$line = substr($line, 0, (strlen($deliminator) * -1));
# add the newline
$line .= "\n";
# we don't care if the file pointer is invalid,
# let fputs take care of it
return $line;
}#end fputcsv()
function fputcsv ($fp, $array, $deliminator=",") {
return fputs($fp, putcsv($array,$delimitator));
}#end fputcsv()
/**
* description
*
* #param
*
* #return
*
* #access
*/
function is_subaction($sub,$action) {
return (bool)($_GET["sub"] == $sub) && ($_GET["action"] == $action);
}
?>
many thanks in advance
fputcsv() is a built in PHP function. This means you cannot name your own function the same thing.
If you need this code to work with PHP4, just check to see if the function exists first, then if not, create your own.
if (!function_exists('fputcsv')) {
// Your definition here
}
I have created a Database Abstraction Layer over PDO to refrain from creating multiple queries around my scripts which would be pretty hard to maintain.
My DBAL is not very broad; It takes care of simple tasks such as INSERTING, UPDATING and SELECTING (with or without joining). It does not cover more advanced stuff such as selecting from multiple tables etc.
The problem that raised with my DBAL is that it is confusing queries when there are more of the same type in one HTTP request. For example there are three select statements in my script, the first one works, the other two don't. I tried creating a flush method to clear the previously filled attributes by the query, but it's not working and I'm out of ideas. I'm not ready to get rid of my class and get back to writing queries all over - it's so easy to write them this way.
Anyway, this is how I do some queries with my class:
$insert_update_select = array(
'COLUMNS' => array(
'column_name1' => 'data_to_update_or_insert1',
'column_name2' => 'data_to_update_or_insert2'
),
'WHERE' => array('x > y', 'y < x'),
'ORDER' => array('ASC' => 'column_name1'),
'LIMIT' => array(0, 5),
);
// This query works with updating, inserting and selecting
$db = new db();
$db->insert('table_name', $insert_update_select);
$db->update('table_name', $insert_update_select);
$db->select('table_name', $insert_update_select);
Don't ask me how to join tables; I actually forgot how my own syntax works for that, haha. (Gotta try to remember)
Anyway, here is my class:
<?php
class db
{
private $db_type = 'mysql';
private $db_host = 'localhost';
private $db_user = 'root';
private $db_pass = '';
private $db_name = 'imgzer';
private $db;
private $db_connection = '';
private $insert_data = '';
private $update_data = '';
private $select_data = '';
private $condition_data = '';
private $order_data = '';
private $limit_data = '';
private $join_data = array();
private $query;
private $table;
private $return_data;
private $affected_rows;
private $return_id;
// Database tables
const USERS_TABLE = 'imgzer_users';
const CONFIG_TABLE = 'imgzer_config';
public function __construct()
{
$this->db_connection = "$this->db_type:host=$this->db_host;dbname=$this->db_name";
$this->db = new PDO($this->db_connection, $this->db_user, $this->db_pass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
unset($this->db_pass);
}
public function open()
{
if ($this->db)
{
return true;
}
return false;
}
public function close()
{
if ($this->db->close())
{
return true;
}
return false;
}
private function build_array($type, $data, $join_data = array())
{
if (empty($data))
{
return;
}
$type = strtoupper($type);
$this->update_data = '';
$this->select_data = '';
$data_index = 0;
$data_length = sizeof($data);
$last_row = $data_length - 1;
switch ($type)
{
case 'INSERT':
if (!is_array($data))
{
return;
}
$this->insert_data = '(';
foreach ($data as $column => $value)
{
$this->insert_data .= $column . (($data_index != $last_row) ? ', ' : '');
$data_index++;
}
$data_index = 0;
$this->insert_data .= ') ';
$this->insert_data .= 'VALUES (';
foreach ($data as $column => $value)
{
$this->insert_data .= '?' . (($data_index != $last_row) ? ', ' : '');
$data_index++;
}
$this->insert_data .= ') ';
break;
case 'UPDATE':
$this->update_data = '';
foreach ($data as $column => $value)
{
$this->update_data .= $column . ' = ?' . (($data_index != $last_row) ? ', ' : '');
$data_index++;
}
break;
case 'SELECT':
if (empty($join_data))
{
return;
}
if (is_array($join_data))
{
$from_table = array_keys($join_data['FROM']);
$join_table = array_keys($join_data['TABLES']);
$this->select_data = implode(', ', array_flip($data)) . ' FROM ' ;
$this->select_data .= $from_table[0] . ' ' . $join_data['FROM'][$from_table[0]] . ' ';
for ($i = 0; $i < sizeof($this->join_data); $i++)
{
$this->select_data .= $this->get_join_type($join_data['JOIN']). ' ';
$this->select_data .= $join_table[$i] . ' ' . $join_data['TABLES'][$join_table[$i]];
$this->select_data .= $this->join_data[$i];
}
$this->select_data = rtrim($this->select_data, ' ');
}
else
{
if (!isset($data[0]))
{
$data = array_flip($data);
}
$this->select_data = implode(', ', $data) . ' FROM ' . $this->table . ' ';
}
break;
}
}
private function set_join($on)
{
if (empty($on))
{
return;
}
if (is_array($on))
{
for ($i = 0; $i < sizeof($on); $i++)
{
$on[$i] = ' ON (' . implode(' AND ', $on[$i]) . ') ';
}
}
$this->join_data = $on;
}
private function set_order($order)
{
if (empty($order))
{
return;
}
$this->order_data = ' ORDER BY ';
if (is_array($order))
{
$data_index = 0;
$data_size = sizeof($order) - 1;
foreach ($order as $order_type => $column)
{
if ($order_type != 'ASC' && $order_type != 'DESC')
{
throw new Exception('Order type in SQL has to be either ASC or DESC');
return;
}
$this->order_data .= $column . ' ' . $order_type . (($data_index != $data_size) ? ', ' : '');
$data_index++;
}
return;
}
$this->order_data .= $order;
}
private function set_limit($limit)
{
if (empty($limit))
{
return;
}
if (sizeof($limit) > 2)
{
return;
}
if (sizeof($limit) == 1)
{
$limit = array(0, $limit[0]);
}
if (is_array($limit))
{
$limit = implode(', ', $limit);
}
$this->limit_data = " LIMIT {$limit}";
}
private function set_where($condition)
{
if (empty($condition))
{
return;
}
if (is_array($condition))
{
$condition = implode(' AND ', $condition);
}
$this->condition_data = " WHERE $condition";
}
public function in_set($where_ary)
{
$where_str = implode(', ', $where_ary);
$where_str = substr($where_str, 0, -2);
$where_str = 'IN (' . $where_str . ')';
return $where_str;
}
/*
* Example usage:
* $insert_ary = array('col_1' => 'col_data_1', 'col_2' => 'col_data_2');
* $condition_ary = array('col_1 > 5', 'col_2 <> 10');
* $order_ary = array('ASC' => 'col_1', 'DESC' => 'col_2');
* $limit = array($start = 0, $limit = 5);
* $instance->insert('my_table', $insert_ary, $condition_ary, $order_ary, $limit);
*/
public function insert($table, $data, $return_id = false)
{
$data = $this->data_abstract($data);
// Prepare the arrays
$this->build_array('INSERT', $data['COLUMNS']);
$this->set_where($data['WHERE']);
$this->set_order($data['ORDER']);
$this->set_limit($data['LIMIT']);
$sql = 'INSERT INTO ' . $table . ' ';
$sql .= $this->insert_data;
$sql .= $this->condition_data;
$sql .= $this->order_data;
$sql .= $this->limit_data;
$this->query = $this->db->prepare($sql);
$param_index = 1;
foreach ($data['COLUMNS'] as $column => &$value)
{
$this->query->bindParam($param_index, $value);
$param_index++;
}
$this->query->execute();
if ($return_id)
{
$this->return_id = $this->query->last_insert_id();
}
else
{
$this->affected_rows = $this->query->rowCount();
}
}
public function update($table, $data, $return_id = false)
{
$data = $this->data_abstract($data);
// Prepare the arrays
$this->build_array('UPDATE', $data['COLUMNS']);
$this->set_where($data['WHERE']);
$this->set_order($data['ORDER']);
$this->set_limit($data['LIMIT']);
$sql = 'UPDATE ' . $table . ' SET ';
$sql .= $this->update_data;
$sql .= $this->condition_data;
$sql .= $this->order_data;
$sql .= $this->limit_data;
$this->query = $this->db->prepare($sql);
$param_index = 1;
foreach ($data['COLUMNS'] as $column => &$value)
{
$this->query->bindParam($param_index, $value);
$param_index++;
}
$this->query->execute();
if ($return_data)
{
$this->return_id = $this->query->last_insert_id();
}
else
{
$this->affected_rows = $this->query->rowCount();
}
}
/*
* Joining example:
* $join_data = array(
* 'TABLES' => array('table_2' => 't2', 'table_3' => 't3'),
* 'JOIN' => 'LEFT',
* 'ON' => array(
* array('colx > 15', 'coly < 20'),
* array('fieldx > 15', 'fieldy < 20')
* ),
*);
*/
public function select($table, $data, $join = false, $fetch_type = 'assoc')
{
$data = $this->data_abstract($data);
if ($join)
{
if (!is_array($table))
{
throw new Exception('Table has to be associated with a short index');
return;
}
$this->set_join($join['ON']);
$table = array_merge(array('FROM' => $table), $join);
}
// Globalize table name if not joins are used
$this->table = $table;
// Prepare the arrays
$this->build_array('SELECT', $data['COLUMNS'], $table);
$this->set_where($data['WHERE']);
$this->set_order($data['ORDER']);
$this->set_limit($data['LIMIT']);
$sql = 'SELECT ';
$sql .= $this->select_data;
$sql .= $this->condition_data;
$sql .= $this->order_data;
$sql .= $this->limit_data;
$this->query = $this->db->prepare($sql);
$result = $this->query->execute();
$fetch_type = ($fetch_type == 'assoc') ? PDO::FETCH_ASSOC : PDO::FETCH_NUM;
$fetched_data = $this->query->fetchAll($fetch_type);
$data_result = $fetched_data;
if (sizeof($fetched_data) == 1)
{
$data_result = $fetched_data[0];
}
$this->return_data = $data_result;
// Clear the result
//$this->query->closeCursor();
}
public function fetch()
{
return $this->return_data;
}
public function affected_rows()
{
return $this->affected_rows;
}
private function data_abstract($data)
{
$abstract_ary = array('COLUMNS' => '', 'WHERE' => '', 'ORDER' => '', 'LIMIT' => 0);
return array_merge($abstract_ary, $data);
}
private function get_join_type($type)
{
switch ($type)
{
default:
case 'LEFT':
return 'LEFT JOIN';
break;
case 'RIGHT':
return 'RIGHT JOIN';
break;
case 'INNER':
return 'INNER JOIN';
break;
case 'NORMAL':
case 'JOIN':
return 'JOIN';
break;
}
}
private function flush()
{
unset($this->query, $this->insert_data, $this->update_data, $this->select_data);
}
}
$db = new db();
?>
What's wrong with it (could be a lot) and how do I actually make it work efficiently?
Don't make it stateful.
Even without looking at the code I'll tell you what's the problem: get rid of $this->stmt variable.
For some reason, all the DBAL writers have strong inclination to such a variable... introducing state to their class and thus making it unusable.
All the method calls have to be atomic, each performing all the necessary operations and returning all the requested data. While saving nothing in the class variables. As simple as that. In such a rare case when PDOStatement object have to be used further - return this very object, don't save it inside. Otherwise just return the requested data.
I wold also advise to get rid of your whole DBAL, as it's written out of good intentions but I can tell for sure that implementation turns out to be less helpful but it actually makes your code worse in many aspects - readability, flexibility, maintainability. In pursue for the fictional usability, you are saving yourself only a word or two from SQL, but making whole application code unreliable.
You won't listen to me, though. Some experience in maintaining applications is required to see my point.
I am getting this PHP fatal error message: "Fatal error: Class PT_Fieldtype contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (EE_Fieldtype::display_field) in /.../pt_fieldtype.php on line 148"
However, when I open the file and do a search, the word "abstract" is nowhere to be found at all. Thanks for the help!
Edit: Here's the code in question. My bad for not showing it before.
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
if (! defined('PT_FIELD_PACK_VER'))
{
// get the version from config.php
require PATH_THIRD.'pt_field_pack/config.php';
define('PT_FIELD_PACK_VER', $config['version']);
}
/**
* P&T Fieldtype Base Class
*
* #package P&T Field Pack
* #author Brandon Kelly <brandon#pixelandtonic.com>
* #copyright Copyright (c) 2010 Pixel & Tonic, LLC
*/
class PT_Fieldtype extends EE_Fieldtype {
/**
* PT_Fieldtype Constructor
*/
function PT_Fieldtype()
{
parent::EE_Fieldtype();
}
// --------------------------------------------------------------------
/**
* Options Setting
*/
function options_setting($options=array(), $indent = '')
{
$r = '';
foreach($options as $name => $label)
{
if ($r !== '') $r .= "\n";
// is this just a blank option?
if (! $name && ! $label) $name = $label = ' ';
$r .= $indent . htmlentities($name);
// is this an optgroup?
if (is_array($label)) $r .= "\n".$this->options_setting($label, $indent.' ');
else if ($name != $label) $r .= ' : '.$label;
}
return $r;
}
// --------------------------------------------------------------------
/**
* Save Options Setting
*/
function save_options_setting($options = '', $total_levels = 1)
{
// prepare options
$options = preg_split('/[\r\n]+/', $options);
foreach($options as &$option)
{
$option_parts = preg_split('/\s:\s/', $option, 2);
$option = array();
$option['indent'] = preg_match('/^\s+/', $option_parts[0], $matches) ? strlen(str_replace("\t", ' ', $matches[0])) : 0;
$option['name'] = trim($option_parts[0]);
$option['value'] = isset($option_parts[1]) ? trim($option_parts[1]) : $option['name'];
}
return $this->_structure_options($options, $total_levels);
}
/**
* Structure Options
*/
private function _structure_options(&$options, $total_levels, $level = 1, $indent = -1)
{
$r = array();
while ($options)
{
if ($indent == -1 || $options[0]['indent'] > $indent)
{
$option = array_shift($options);
$children = (! $total_levels OR $level < $total_levels)
? $this->_structure_options($options, $total_levels, $level+1, $option['indent']+1)
: FALSE;
$r[(string)$option['name']] = $children ? $children : (string)$option['value'];
}
else if ($options[0]['indent'] <= $indent)
{
break;
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Prep Iterators
*/
function prep_iterators(&$tagdata)
{
// find {switch} tags
$this->_switches = array();
$tagdata = preg_replace_callback('/'.LD.'switch\s*=\s*([\'\"])([^\1]+)\1'.RD.'/sU', array(&$this, '_get_switch_options'), $tagdata);
$this->_count_tag = 'count';
$this->_iterator_count = 0;
}
/**
* Get Switch Options
*/
function _get_switch_options($match)
{
global $FNS;
$marker = LD.'SWITCH['.$FNS->random('alpha', 8).']SWITCH'.RD;
$this->_switches[] = array('marker' => $marker, 'options' => explode('|', $match[2]));
return $marker;
}
/**
* Parse Iterators
*/
function parse_iterators(&$tagdata)
{
// {switch} tags
foreach($this->_switches as $i => $switch)
{
$option = $this->_iterator_count % count($switch['options']);
$tagdata = str_replace($switch['marker'], $switch['options'][$option], $tagdata);
}
// update the count
$this->_iterator_count++;
// {count} tags
$tagdata = $this->EE->TMPL->swap_var_single($this->_count_tag, $this->_iterator_count, $tagdata);
}
}
// ====================================================================
/**
* P&T Multi Fieldtype Base Class
*
* #package P&T Field Pack
* #author Brandon Kelly <brandon#pixelandtonic.com>
* #copyright Copyright (c) 2010 Pixel & Tonic, LLC
*/
class PT_Multi_Fieldtype extends PT_Fieldtype {
var $default_field_settings = array(
'options' => array(
'Option 1' => 'Option 1',
'Option 2' => 'Option 2',
'Option 3' => 'Option 3'
)
);
var $default_cell_settings = array(
'options' => array(
'Opt 1' => 'Opt 1',
'Opt 2' => 'Opt 2'
)
);
var $default_tag_params = array(
'sort' => '',
'backspace' => '0'
);
var $total_option_levels = 1;
// --------------------------------------------------------------------
/**
* Display Field Settings
*/
function display_settings($data)
{
// load the language file
$this->EE->lang->loadfile($this->class);
$options = isset($data['options']) ? $data['options'] : array();
$input_name = $this->class.'_options';
$this->EE->table->add_row(
lang($this->class.'_options', $input_name) . '<br />'
. lang('field_list_instructions') . '<br /><br />'
. lang('option_setting_examples'),
'<textarea id="'.$input_name.'" name="'.$input_name.'" rows="6">'.$this->options_setting($options).'</textarea>'
);
}
/**
* Display Cell Settings
*/
function display_cell_settings($data)
{
// load the language file
$this->EE->lang->loadfile($this->class);
$options = isset($data['options']) ? $data['options'] : array();
return array(
array(
lang($this->class.'_options'),
'<textarea class="matrix-textarea" name="options" rows="4">'.$this->options_setting($options).'</textarea>'
)
);
}
// --------------------------------------------------------------------
/**
* Save Field Settings
*/
function save_settings($data)
{
$post = $this->EE->input->post($this->class.'_options');
// replace quotes
$post = str_replace('"', '"', $post);
return array(
'options' => $this->save_options_setting($post, $this->total_option_levels)
);
}
/**
* Save Cell Settings
*/
function save_cell_settings($settings)
{
// replace quotes
$settings['options'] = str_replace('"', '"', $settings['options']);
$settings['options'] = $this->save_options_setting($settings['options'], $this->total_option_levels);
return $settings;
}
// --------------------------------------------------------------------
/**
* Prep Field Data
*
* Ensures $field_data is an array.
*/
function prep_field_data(&$data)
{
if (! is_array($data))
{
$data = array_filter(preg_split("/[\r\n]+/", $data));
}
}
// --------------------------------------------------------------------
/**
* Display Field
*/
function display_field($data)
{
if (is_string($data)) $data = html_entity_decode($data);
return $this->_display_field($data, $this->field_name);
}
/**
* Display Cell
*/
function display_cell($data)
{
return $this->_display_field($data, $this->cell_name);
}
// --------------------------------------------------------------------
/**
* Save
*/
function save($data)
{
// replace quotes
return str_replace('"', '"', $data);
}
/**
* Save Cell
*/
function save_cell($data)
{
// replace quotes
return $this->save($data);
}
// --------------------------------------------------------------------
/**
* Find Options
*/
private function _find_option($needle, $haystack)
{
foreach ($haystack as $key => $value)
{
$r = $value;
if ($needle == $key OR (is_array($value) AND (($r = $this->_find_option($needle, $value)) !== FALSE)))
{
return $r;
}
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Replace Tag
*/
function replace_tag($data, $params = array(), $tagdata = FALSE)
{
if (! isset($this->settings['options']) || ! $this->settings['options'])
{
return $data;
}
if (! $tagdata)
{
return $this->replace_ul($data, $params);
}
$this->prep_field_data($data);
$r = '';
if ($this->settings['options'] && $data)
{
// optional sorting
if (isset($params['sort']) && $params['sort'])
{
$sort = strtolower($params['sort']);
if ($sort == 'asc')
{
sort($data);
}
else if ($sort == 'desc')
{
rsort($data);
}
}
// offset and limit
if (isset($params['offset']) || isset($params['limit']))
{
$offset = isset($params['offset']) ? $params['offset'] : 0;
$limit = isset($params['limit']) ? $params['limit'] : count($data);
$data = array_splice($data, $offset, $limit);
}
// prepare for {switch} and {count} tags
$this->prep_iterators($tagdata);
foreach($data as $option_name)
{
if (($option = $this->_find_option($option_name, $this->settings['options'])) !== FALSE)
{
// copy $tagdata
$option_tagdata = $tagdata;
// simple var swaps
$option_tagdata = $this->EE->TMPL->swap_var_single('option', $option, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('option_name', $option_name, $option_tagdata);
// parse {switch} and {count} tags
$this->parse_iterators($option_tagdata);
$r .= $option_tagdata;
}
}
if (isset($params['backspace']) && $params['backspace'])
{
$r = substr($r, 0, -$params['backspace']);
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Unordered List
*/
function replace_ul($data, $params = array())
{
return "<ul>\n"
. $this->replace_tag($data, $params, " <li>{option}</li>\n")
. '</ul>';
}
/**
* Ordered List
*/
function replace_ol($data, $params = array())
{
return "<ol>\n"
. $this->replace_tag($data, $params, " <li>{option}</li>\n")
. '</ol>';
}
// --------------------------------------------------------------------
/**
* All Options
*/
function replace_all_options($data, $params = array(), $tagdata = FALSE, $options = FALSE, $iterator_count = 0)
{
if (! $tagdata)
{
return "<ul>\n"
. $this->replace_all_options($data, $params, " <li>{option}</li>\n")
. "</ul>";
}
PT_Multi_Fieldtype::prep_field_data($data);
$r = '';
if ($options === FALSE)
{
$options = $this->settings['options'];
}
if ($options)
{
// optional sorting
if (isset($params['sort']) && $params['sort'])
{
$sort = strtolower($params['sort']);
if ($sort == 'asc')
{
asort($options);
}
else if ($sort == 'desc')
{
arsort($options);
}
}
// prepare for {switch} and {count} tags
$this->prep_iterators($tagdata);
$this->_iterator_count += $iterator_count;
foreach($options as $option_name => $option)
{
if (is_array($option))
{
$sub_params = array_merge($params, array('backspace' => '0'));
$r .= $this->replace_all_options($data, $sub_params, $tagdata, $option, $this->_iterator_count);
}
else
{
// copy $tagdata
$option_tagdata = $tagdata;
// simple var swaps
$option_tagdata = $this->EE->TMPL->swap_var_single('option', $option, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('option_name', $option_name, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('selected', (in_array($option_name, $data) ? 1 : 0), $option_tagdata);
// parse {switch} and {count} tags
$this->parse_iterators($option_tagdata);
$r .= $option_tagdata;
}
}
if (isset($params['backspace']) && $params['backspace'])
{
$r = substr($r, 0, -$params['backspace']);
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Is Selected?
*/
function replace_selected($data, $params = array())
{
$this->prep_field_data($data);
return (isset($params['option']) AND in_array($params['option'], $data)) ? 1 : 0;
}
/**
* Total Selections
*/
function replace_total_selections($data, $params = array())
{
$this->prep_field_data($data);
return $field_data ? (string) count($data) : '0';
}
}
The answer of your question is on line 148 of this file...
Maybe you are using a class with abstract methods without inheriting them that is rejected, make sure you implement all of them and after show us some code. ;-)