OpenCart Can I run this code to recreate my Category_Path table - opencart2.x

I had an unfortunate incident with an Import/Export Extension that ate my Category_Path table data. Now none of my categories show up in the front or backend of my site.
Will the code below work to recreate my category_path table in OpenCart 2.1.0.1?
If so how do I go about implementing it?
<?php
// Configuration
if (is_file('config.php')) {
require_once('config.php');
}
// Startup
require_once(DIR_SYSTEM . 'startup.php');
// Registry
$registry = new Registry();
// Config
$config = new Config();
$registry->set('config', $config);
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);
class myClass
{
protected $db;
public function __construct($db)
{
$this->db = $db;
}
// Database
function repairCategories($parent_id = 0)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "category` WHERE `parent_id` = '" .
(int)$parent_id . "'");
echo "SELECT * FROM `" . DB_PREFIX . "category` WHERE `parent_id` = '" . (int)$parent_id .
"'<br><br>";
foreach ($query->rows as $row)
{
// Delete the path below the current one
echo "DELETE FROM `" . DB_PREFIX . "category_path` WHERE `category_id` = '" . (int)$row
['category_id'] . "'<br>";
$this->db->query("DELETE FROM `" . DB_PREFIX . "category_path` WHERE `category_id` = '" .
(int)$row['category_id'] . "'");
// Fix for records with no paths
$level = 0;
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "category_path` WHERE
`category_id` = '" . (int)$parent_id . "' ORDER BY `level` ASC");
echo "SELECT * FROM `" . DB_PREFIX . "category_path` WHERE `category_id` = '" .
(int)$parent_id . "' ORDER BY `level` ASC<br>";

Related

Custom pagination query error in CakePHP

I am new in CakePHP. Now, I am using cakephp (version 2.8.5).
I try to create custom query pagination because I need to join multiple tables. But, its not work and I got Unsupported operand types error.
In my User model, I try to create paginate() and paginateCount() function as shown in below.
public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
$recursive = -1;
// // Mandatory to have
// $this->useTable = false;
$sql = '';
$sql .= "SELECT u.id,u.name, u.password, r.display_name, GROUP_CONCAT(p.display_name SEPARATOR ', ') as per_name ";
$sql .= "FROM `users` u ";
$sql .= "LEFT JOIN roles r ON (u.role_id = r.id) ";
$sql .= "LEFT JOIN user_permission up ON (u.id = up.user_id) ";
$sql .= "LEFT JOIN permissions p ON (up.permission = p.id) ";
$sql .= "WHERE 1 GROUP BY u.name ORDER BY u.id ";
// Adding LIMIT Clause
$sql .= "LIMIT ".(($page - 1) * $limit) . ', ' . $limit;
$results = $this->query($sql);
return $results;
}
public function paginateCount($conditions = null, $recursive = 0,
$extra = array()) {
$sql = '';
$sql .= "SELECT COUNT(*) as count FROM
(SELECT u.id,u.name, u.password, r.display_name, GROUP_CONCAT(p.display_name SEPARATOR ', ') as per_name
FROM `users` u
LEFT JOIN roles r ON (u.role_id = r.id) LEFT JOIN user_permission up ON (u.id = up.user_id)
LEFT JOIN permissions p ON (up.permission = p.id)
WHERE 1
GROUP BY u.name
ORDER BY u.id ) AS Temp";
$this->recursive = $recursive;
$results = $this->query($sql);
return $results;
}
In my UsersController,
public function index() {
$users = $this->User->getAllUser();
//for pagination
$this->paginate = array(
'limit' => 4
);
$page = $this->paginate();
$count = $this->paginateCount();
$this->set('page',$page);
$this->set('rowCount',$count);
$this->set('users',$users);
$this->render('index');
}
But its not work and I got Unsupported operand types fatal error. I think may be I was wrong in here($this->paginate()). But actually not sure what is wrong in my code.
I already searching a lot of place on web and can't solve. I'm very appreciate for any suggestion.
Ok, now I understand what's wrong in my code.
Problem is not in controller. I was wrong when I return $results in paginateCount() function. The correct way to returning the result must be like return $results[0][0]['count']; in the paginateCount() function.
Because the query result in paginateCount() will return like this:
array(1) { [0]=> array(1) { [0]=> array(1) { ["count"]=> string(1) "5"
} } }
Complete code for paginateCount() is as shown in below.
public function paginateCount($conditions = null, $recursive = 0,
$extra = array()) {
$sql = '';
$sql = "SELECT COUNT(*) as count FROM
(SELECT User.id,User.name, User.password, r.display_name, GROUP_CONCAT(p.display_name SEPARATOR ', ') as per_name
FROM `users` User
LEFT JOIN roles r ON (User.role_id = r.id) LEFT JOIN user_permission up ON (User.id = up.user_id)
LEFT JOIN permissions p ON (up.permission = p.id)
WHERE 1
GROUP BY User.name
ORDER BY User.id ) AS Temp";
$this->recursive = $recursive;
$results = $this->query($sql);
return $results[0][0]['count'];
}

Pagination cannot move next

I want to display records from database using pagination, I am using the the code below it display the limit but when moving the next page or records it cannot load.
How to fix pagination moving next cannot load or move to page 2?
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'admin121';
$rec_limit = 10;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('misdb');
$sql = "SELECT count(S_ID) FROM student";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];
if( isset($_GET{'page'}) ) {
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
} else {
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
$sql = "SELECT S_ID, LastName, FirstName ".
"FROM student ".
"LIMIT $offset, $rec_limit";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['S_ID']} <br> ".
"EMP NAME : {$row['LastName']} <br> ".
"EMP SALARY : {$row['FirstName']} <br> ".
"--------------------------------<br>";
}
if( $page > 0 ) {
$last = $page - 2;
echo "Last 10 Records |";
echo "Next 10 Records";
} else if( $page == 1 ) {
echo "Next 10 Records";
} else if( $left_rec < $rec_limit ) {
$last = $page - 2;
echo "Last 10 Records";
}
You only need to remove white spaces, so change this:
\"$_PHP_SELF?page = $last\"
Into this:
\"$_PHP_SELF?page=$last\"

Opencart 2.x Event name in called function

So I have 3 events who call the same function.
Would it be possible to obtain the event name directly in the function?
$this->model_extension_event->addEvent('postorderchange', 'post.order.edit', 'module/postorderchange/on_order_change');
$this->model_extension_event->addEvent('postorderchange', 'post.order.add', 'module/postorderchange/on_order_change');
$this->model_extension_event->addEvent('postorderchange', 'post.order.history.add', 'module/postorderchange/on_order_change');
I want to be able to get the name of the event in the on_order_change() function.
post.order.history.add event trigger the total/voucher/send action.
you can check send function in following file.
catalog/controller/total/voucher.php
Inside the function : -
public function send($order_id) {
$this->load->model('checkout/order');
$order_info = $this->model_checkout_order->getOrder($order_id);
// If order status in the complete range create any vouchers that where in the order need to be made available.
if (in_array($order_info['order_status_id'], $this->config->get('config_complete_status'))) {
$voucher_query = $this->db->query("SELECT *, vtd.name AS theme FROM `" . DB_PREFIX . "voucher` v LEFT JOIN " . DB_PREFIX . "voucher_theme vt ON (v.voucher_theme_id = vt.voucher_theme_id) LEFT JOIN " . DB_PREFIX . "voucher_theme_description vtd ON (vt.voucher_theme_id = vtd.voucher_theme_id) WHERE v.order_id = '" . (int)$order_info['order_id'] . "' AND vtd.language_id = '" . (int)$order_info['language_id'] . "'");
if ($voucher_query->num_rows) {
// Send out any gift voucher mails
$language = new Language($order_info['language_directory']);
$language->load($order_info['language_directory']);
$language->load('mail/voucher');
foreach ($voucher_query->rows as $voucher) {
// HTML Mail
$data = array();
$data['title'] = sprintf($language->get('text_subject'), $voucher['from_name']);
$data['text_greeting'] = sprintf($language->get('text_greeting'), $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']));
$data['text_from'] = sprintf($language->get('text_from'), $voucher['from_name']);
$data['text_message'] = $language->get('text_message');
$data['text_redeem'] = sprintf($language->get('text_redeem'), $voucher['code']);
$data['text_footer'] = $language->get('text_footer');
if (is_file(DIR_IMAGE . $voucher['image'])) {
$data['image'] = $this->config->get('config_url') . 'image/' . $voucher['image'];
} else {
$data['image'] = '';
}
$data['store_name'] = $order_info['store_name'];
$data['store_url'] = $order_info['store_url'];
$data['message'] = nl2br($voucher['message']);
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/mail/voucher.tpl')) {
$html = $this->load->view($this->config->get('config_template') . '/template/mail/voucher.tpl', $data);
} else {
$html = $this->load->view('default/template/mail/voucher.tpl', $data);
}
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($voucher['to_email']);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender(html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'));
$mail->setSubject(html_entity_decode(sprintf($language->get('text_subject'), $voucher['from_name']), ENT_QUOTES, 'UTF-8'));
$mail->setHtml($html);
$mail->send();
}
}
}
}
You can modified here..

How to import the excel file to mySQL database using php

I want to import the data in the excel to mySQL DB using php. I have tried using the way explained in other questions but nothing worked out for me. Kindly let me know how to import the data in to DB using php.
Also, do let me know where to place the excel file to be uploaded,I mean the location in the system.
method 1.you can use load data command
http://blog.tjitjing.com/index.php/2008/02/import-excel-data-into-mysql-in-5-easy.html
method 2. Excel reader
https://code.google.com/p/php-excel-reader/
method 3. parseCSV
https://github.com/parsecsv/parsecsv-for-php
method4. (PHP 4, PHP 5) fgetcsv
http://in1.php.net/fgetcsv
please refer this PHP code
<?php
//table Name
$tableName = "MyTable";
//database name
$dbName = "MyDatabase";
$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db($dbName) or die(mysql_error());
//get the first row fields
$fields = "";
$fieldsInsert = "";
if (($handle = fopen("test.csv", "r")) !== FALSE) {
if(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$fieldsInsert .= '(';
for ($c=0; $c < $num; $c++) {
$fieldsInsert .=($c==0) ? '' : ', ';
$fieldsInsert .="`".$data[$c]."`";
$fields .="`".$data[$c]."` varchar(500) DEFAULT NULL,";
}
$fieldsInsert .= ')';
}
//drop table if exist
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$tableName."'"))>=1) {
mysql_query('DROP TABLE IF EXISTS `'.$tableName.'`') or die(mysql_error());
}
//create table
$sql = "CREATE TABLE `".$tableName."` (
`".$tableName."Id` int(100) unsigned NOT NULL AUTO_INCREMENT,
".$fields."
PRIMARY KEY (`".$tableName."Id`)
) ";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
else {
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$fieldsInsertvalues="";
//get field values of each row
for ($c=0; $c < $num; $c++) {
$fieldsInsertvalues .=($c==0) ? '(' : ', ';
$fieldsInsertvalues .="'".$data[$c]."'";
}
$fieldsInsertvalues .= ')';
//insert the values to table
$sql = "INSERT INTO ".$tableName." ".$fieldsInsert." VALUES ".$fieldsInsertvalues;
mysql_query($sql,$conn);
}
echo 'Table Created';
}
fclose($handle);
}
?>

Paypal Success transation return values empty-- sometimes

There is a problem with my paypal Integration in live site.
For 90% of transactions, I didn't get any problem. Some times only I am facing this below problem.
Problem: After successful transaction, I am not getting Pay pal values like Transaction Id, Message etc. All values shows empty. It comes for 10% of transactions only. please tell me what may be the problem. Can't able to find out the reason
Thanks in Advance..
$paypal_email = '5345345345345f';
$cur_dir='http://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
$return_url = $cur_dir.'/paymentsucess.php';
$cancel_url = $cur_dir.'/payment-not-sucess.php';
$notify_url = $cur_dir.'/payments.php';
extract($_POST);
$item_name = $exam_name;
$item_amount = $amount;
$userid=$userid;
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
$querystring = "?business=".urlencode($paypal_email)."&";
$querystring .= "item_name=".urlencode($item_name)."&";
$querystring .= "amount=".urlencode($item_amount)."&";
//loop for posted values and append to querystring
foreach($_POST as $key => $value){
$value = urlencode(stripslashes($value));
$querystring .= "$key=$value&";
}
$querystring .= "return=".urlencode(stripslashes($return_url))."&";
$querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
$querystring .= "notify_url=".urlencode($notify_url);
header('location:https://www.paypal.com/cgi-bin/webscr'.$querystring);
exit();
}else{
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$value = preg_replace('/(.*[^%^0^D])(%0A) (.*)/i','${1}%0D%0A${3}',$value);// IPN fix
$req .= "&$key=$value";
}
$data['item_name'] = $_POST['item_name'];
$data['item_number'] = $_POST['item_number'];
$data['payment_status'] = $_POST['payment_status'];
$data['payment_amount'] = $_POST['mc_gross'];
$data['payment_currency'] = $_POST['mc_currency'];
$data['txn_id'] = $_POST['txn_id'];
$data['receiver_email'] = $_POST['receiver_email'];
$data['payer_email'] = $_POST['payer_email'];
$data['custom'] = $_POST['custom'];
$data['userid'] = $_POST['userid'];
// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
// Validate payment (Check unique txnid & correct price)
$valid_txnid = check_txnid($data['txn_id']);
$valid_price = check_price($data['payment_amount'], $data['item_number']);
// PAYMENT VALIDATED & VERIFIED!
if($valid_txnid && $valid_price){
$orderid = updatePayments($data);
if($orderid){
}else{
}
}else{
}
}else if (strcmp ($res, "INVALID") == 0) {
}
}
fclose ($fp);
}
}

Resources