"An error occured while communicating to the server." - using Jtables - mysqli

I am trying to use the "Using jTable with PHP" sample http://www.jtable.org/Home/Downloads, but when I run the program and changed "mysql" functions to "mysqli", I can't connect to the database and got the error: "An error occured while communicating to the server"
I am new with using mysqli, I tried to search all day but ended up with nothing.
jTableSimplePagedSorted.php
<html>
<head>
<link href="themes/redmond/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
<link href="Scripts/jtable/themes/lightcolor/blue/jtable.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<script src="Scripts/jtable/jquery.jtable.js" type="text/javascript"></script>
</head>
<body>
<div id="PeopleTableContainer" style="width: 600px;"></div>
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#PeopleTableContainer').jtable({
title: 'Table of people',
paging: true,
pageSize: 2,
sorting: true,
defaultSorting: 'Name ASC',
actions: {
listAction: 'PersonActionsPagedSorted.php?action=list',
createAction: 'PersonActionsPagedSorted.php?action=create',
updateAction: 'PersonActionsPagedSorted.php?action=update',
deleteAction: 'PersonActionsPagedSorted.php?action=delete'
},
fields: {
PersonId: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Author Name',
width: '40%'
},
Age: {
title: 'Age',
width: '20%'
},
RecordDate: {
title: 'Record date',
width: '30%',
type: 'date',
create: false,
edit: false
}
}
});
//Load person list from server
$('#PeopleTableContainer').jtable('load');
});
</script>
</body>
</html>
PersonActionsPagedSorted.php
<?php
try
{
//Open database connection
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con, "jtabletestdb");
//Getting records (listAction)
if(isset($_GET["action"]) || "list")
{
//Get record count
$result = mysqli_query("SELECT COUNT(*) AS RecordCount FROM people;");
$row = mysqli_fetch_array($result);
$recordCount = $row['RecordCount'];
//Get records from database
$result = mysqli_query("SELECT * FROM people ORDER BY " . $_GET["jtSorting"] . " LIMIT " . $_GET["jtStartIndex"] . "," . $_GET["jtPageSize"] . ";");
//Add all records to an array
$rows = array();
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
//Creating a new record (createAction)
else if(isset($_GET["action"]) == "create")
{
//Insert record into database
$result = mysqli_query("INSERT INTO people(Name, Age, RecordDate) VALUES('" . $_POST["Name"] . "', " . $_POST["Age"] . ",now());");
//Get last inserted record (to return to jTable)
$result = mysqli_query("SELECT * FROM people WHERE PersonId = LAST_INSERT_ID();");
$row = mysqli_fetch_array($result);
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Record'] = $row;
print json_encode($jTableResult);
}
//Updating a record (updateAction)
else if(isset($_GET["action"]) == "update")
{
//Update record in database
$result = mysqli_query("UPDATE people SET Name = '" . $_POST["Name"] . "', Age = " . $_POST["Age"] . " WHERE PersonId = " . $_POST["PersonId"] . ";");
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
//Deleting a record (deleteAction)
else if(isset($_GET["action"]) == "delete")
{
//Delete from database
$result = mysqli_query("DELETE FROM people WHERE PersonId = " . $_POST["PersonId"] . ";");
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
//Close database connection
mysqli_close($con);
}
catch(Exception $ex)
{
//Return error message
$jTableResult = array();
$jTableResult['Result'] = "ERROR";
$jTableResult['Message'] = $ex->getMessage();
print json_encode($jTableResult);
}
?>

Use this syntax to connect to a database:
mysqli_connect(host,username,password,dbname,port,socket);
Here is a link to the example.

{
//Open database connection
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con, "jtabletestdb");
//Getting records (listAction)
if(isset($_GET["action"]) || "list")
{
//Get record count
$result = mysqli_query($con, "SELECT COUNT(*) AS RecordCount FROM people;"); //just add $con
$row = mysqli_fetch_array($result);
$recordCount = $row['RecordCount'];
//Get records from database
$result = mysqli_query($con, "SELECT * FROM people ORDER BY " . $_GET["jtSorting"] . " LIMIT " . $_GET["jtStartIndex"] . "," . $_GET["jtPageSize"] . ";"); //just add $con
//Add all records to an array
$rows = array();
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}

Related

Real Time Reporting API : Fatal error: Call to a member function get() on a non-object

<?php if (is_null($_SESSION['auth']['id'] )) {
$where = "login='" . $_SESSION['auth']['login'] . "'";
header('location: /khawla/index.php');
}
?>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-111358192-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-111358192-1');
</script>
</head>
<body> <?php
$optParams = array(
'dimensions' => 'rt:medium');
try {
$results = $analytics->data_realtime->get(
'ga:UA-111358192-1',
'rt:activeUsers',
$optParams);
// Success.
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();
}
function printRealtimeReport($results) {
printReportInfo($results);
printQueryInfo($results);
printProfileInfo($results);
printColumnHeaders($results);
printDataTable($results);
printTotalsForAllResults($results);
}
function printDataTable(&$results) {
if (count($results->getRows()) > 0) {
$table .= '<table>';
// Print headers.
$table .= '<tr>';
foreach ($results->getColumnHeaders() as $header) {
$table .= '<th>' . $header->name . '</th>';
}
$table .= '</tr>';
// Print table rows.
foreach ($results->getRows() as $row) {
$table .= '<tr>';
foreach ($row as $cell) {
$table .= '<td>'
. htmlspecialchars($cell, ENT_NOQUOTES)
. '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
} else {
$table .= '<p>No Results Found.</p>';
}
print $table;
}
function printColumnHeaders(&$results) {
$html = '';
$headers = $results->getColumnHeaders();
foreach ($headers as $header) {
$html .= <<<HTML
<pre>
Column Name = {$header->getName()}
Column Type = {$header->getColumnType()}
Column Data Type = {$header->getDataType()}
</pre>
HTML;
}
print $html;
}
function printQueryInfo(&$results) {
$query = $results->getQuery();
$html = <<<HTML
<pre>
Ids = {$query->getIds()}
Metrics = {$query->getMetrics()}
Dimensions = {$query->getDimensions()}
Sort = {$query->getSort()}
Filters = {$query->getFilters()}
Max Results = {$query->getMax_results()}
</pre>
HTML;
print $html; }
function printProfileInfo(&$results) {
$profileInfo = $results->getProfileInfo();
$html = <<<HTML
<pre>
Account ID = {$profileInfo->getAccountId()}
Web Property ID = {$profileInfo->getWebPropertyId()}
Internal Web Property ID = {$profileInfo->getInternalWebPropertyId()}
Profile ID = {$profileInfo->getProfileId()}
Profile Name = {$profileInfo->getProfileName()}
Table ID = {$profileInfo->getTableId()}
</pre>
HTML;
print $html;
}
function printReportInfo(&$results) {
$html = <<<HTML
<pre>
Kind = {$results->getKind()}
ID = {$results->getId()}
Self Link = {$results->getSelfLink()}
Total Results = {$results->getTotalResults()}
</pre>
HTML;
print $html;
}
function printTotalsForAllResults(&$results) {
$totals = $results->getTotalsForAllResults();
foreach ($totals as $metricName => $metricTotal) {
$html .= "Metric Name = $metricName\n";
$html .= "Metric Total = $metricTotal";
}
print $html;
}
i have this error when i use Real Time Reporting API even though i modified my id and i can't understand where is the problem
error

SugarCRM 6.5 How to print php template?

I am newly SugarCRM 6.5 developer, I have write view.detail.php file and controller file. How to print template controller action json data php template. please help me. I have create controller and view.details code below.
Controller
protected function action_printinvoice(){
global $current_user, $db, $region;
$db = DBManagerFactory::getInstance();
$id = $_POST['record'];
$sql = "select gn.client_name, gn.client_address, gn.client_address_city, gn.client_address_state, gn.client_address_country, gn.client_address_postalcode, gn.id, gn.recipient_name, gn.recipient_address_city, gn.recipient_address_state, gn.recipient_address_country, gn.recipient_address_postalcode, gn.recipient_address, gn.recipient_vat_id, gn.recipient_tax_no, gn.recipient_name, gn.invoice_number as ginvo_client_invoice_id, "
. " gcstm.* "
. "from ginvo_client_invoice as gn "
. " inner join ginvo_client_invoice_cstm as gcstm on gn.id=gcstm.id_c "
. "where "
. " gn.deleted=0 and gn.id='".$id."' limit 1 ";
$result = $db->query($sql);
$ginv_invoice_ary=array();
while($row = $db->fetchByAssoc($result) ) {
$ginv_invoice_ary[]=$row;
}
if ($ginv_invoice_ary[0]['region_c'] == 'non_eu_client_and_freelancer_provider') {
$region = 'Non EU client and freelancer provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'non_eu_client_and_employed_provider'){
$region = 'Non EU client and employed provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'german_client_and_freelancer_provider'){
$region = 'German client and freelancer provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'german_client_and_employed_provider'){
$region = 'German client and employed provider';
}else if($ginv_invoice_ary[0]['region_c'] == 'eu_client_and_freelancer_provider'){
$region = 'EU client and freelancer provider';
}else if ($ginv_invoice_ary[0]['region_c'] == 'eu_client_and_employed_provider') {
$region = 'EU client and employed provider';
}else {
$region = '';
}
echo json_encode($ginv_invoice_ary);
$this->view = 'invoiceprint';
//$this->view = 'custom/modules/ginvo_client_invoice/metadata/ClientInvoice.php';
exit;
}
View.detail.php
<?php
require_once('include/MVC/View/views/view.detail.php');
// require_once('modules/ginvo_client_invoice/view/invoice.php');
class ginvo_client_invoiceViewDetail extends ViewDetail {
function ginvo_client_invoiceViewDetail(){
parent::ViewDetail();
}
function display(){
echo $ginv_invoice_ary;
//$this->populateQuoteTemplates();
$this->displayPopupHtml();
parent::display();
}
function populateQuoteTemplates(){
global $app_list_strings, $current_user;
$inv_id = $this->bean->id;
$sql = "SELECT * FROM ginvo_client_invoice WHERE deleted=0 AND id='$inv_id'";
$res = $this->bean->db->query($sql);
$app_list_strings[] = array();
while($row = $this->bean->db->fetchByAssoc($res)){
if($row){
$app_list_strings[$row] = $row;
}
}
}
function displayPopupHtml(){
global $app_list_strings,$app_strings, $mod_strings;
$templates = array_keys($app_list_strings);
if($templates){
echo '
<script>
function showPopup(task){
var record = \''.$this->bean->id.'\';
var fdata = {\'record\':record};
var params = jQuery.param(fdata);
$.ajax({
type:\'post\',
data: fdata,
// dataType: "json",
// url:\'custom/client_invoice.php?\'+params,
//url:\'custom/modules/ginvo_client_invoice/ClientInvoice.php?\'+params,
url:\'index.php?module=ginvo_client_invoice&action=printinvoice\',
error:function(resp){},
success:function(resp){
console.log(resp);
// location.reload(true);
}
});
// var w = window.open(\'custom/ClientInvoice.php\');
//
// $(w).ready(function(){
// w.print();
// });
}
</script>';
}
else{
echo '<script>
function showPopup(task){
alert(\''.$current_user.'\');
}
</script>';
}
}
}
?>

Changed mysql to mysqli and can't connect to database

I am not very experienced in this field so this is why I am seeking help.
I recently changed hosts and a script stopped working. After moving all files the new hosts said mysql is deprecated, so after doing a bit of search I decided to change mysql with mysqli and that deprecated error was gone. But now I get a new error (error select db). I think I must make adidtional changes to the script to connect mysqli. This is the file I have
<?php
class Model{
var $conn;
public function openDb($dbhost, $dbuser, $dbpass, $dbname, $conn)
{
//echo "Se creo la conexion ";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysqli');
mysqli_select_db($dbname) or die('Error select db');
mysqli_query("SET NAMES utf8");
return $conn;
}
public function closeDb($conn)
{
mysqli_close($conn);
}
public function query($query)
{
if ($result = mysqli_query($query) or die("Error de Query: </br >" . mysqli_error()."<br/>".$query)) {
//if ($result = mysqli_query($query)) {
} else {
$result = false;
}
return $result;
}
function __construct()
{
$this->openDb(dbhost, dbuser, dbpass, dbname, $conn);
}
//insertGenerico con indedices asiciativos
function insertar($tabla, $datos)
{
$columnas = implode(", ", array_keys($datos));
$valores = implode(", ", $datos);
$query = "INSERT INTO $tabla
($columnas)
VALUES
(" . $valores . ")";
return $this -> query($query);
}
function insertarRelacionArray($tabla, $tablaRelacion, $datos)
{
foreach ($datos as $row) {
$query = "INSERT INTO $tabla
($tablaRelacion[0],$tablaRelacion[2])
VALUES
($tablaRelacion[1],$row)";
//echo '<br>'.$query;
$this -> query($query);
}
}
//getGenerico
function get($tabla, $where = false, $order = false)
{
$query = "SELECT *
FROM $tabla
$where
$order";
return $this -> query($query);
}
//deleteGenerico
function delete($tabla, $id, $idTag = false)
{
if($idTag==false)
$idTag = "id";
$query = "DELETE FROM $tabla
WHERE $idTag = $id";
return $this -> query($query);
}
//update generico
function update($tabla, $datos, $id, $idTag = false)
{
$columnas = array_keys($datos);
$SET = 'SET ';
$i = 0;
foreach ($datos as $key => $value) {
if (next($datos)) {
$SET .= "$key = $value ,";
} else {
$SET .= "$key = $value ";
}
}
if($idTag==false)
$idTag = "id";
$query = "UPDATE $tabla $SET WHERE $idTag = $id;";
return $this -> query($query);
}
}
?>
As described on http://php.net/manual/en/mysqli.select-db.php first parameter should be $link.
bool mysqli_select_db ( mysqli $link , string $dbname )
So change
mysqli_select_db($dbname) or die('Error select db');
to
mysqli_select_db($conn, $dbname) or die('Error select db');
and it should work.
I think that you need to return $conn in your _construct function too, or store it in the object ($this->conn = $conn) so you can use it again.
In addition (thanks to Ki Jéy) you should also update
mysql_query($query)
to
mysqli_query($conn, $query)
and
mysql_real_escape_string($string)
to
mysqli_real_escape_string ($conn, $string)

Magento - Upload file in contact form

I have to create a new field in contact form to upload file.
I followed tuts and this is what i did :
in form.phtml :
<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post" enctype="multipart/form-data">
Then i added the field in the contact form :
<li>
<label for="attachment"><?php echo Mage::helper('contacts')->__('Attachment') ?></label>
<div class="input-box">
<input name="MAX_FILE_SIZE" type="hidden" value="2000000" />
<input name="attachment" id="attachment" class="input-text" type="file" />
</div>
I modified the IndexController.php in : /www/app/code/core/Mage/Contacts/controllers as :
<?php
/**
* Contacts index controller
*
* #category Mage
* #package Mage_Contacts
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_Contacts_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/email/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/email/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/email/email_template';
const XML_PATH_ENABLED = 'contacts/contacts/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('contactForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
/**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts';
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path . DS, $fileName );
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************//**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf', 'jpg', 'jpeg', 'png', 'bmp', 'gif'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts';
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path . DS, $fileName );
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************/
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
/**************************************************************/
//sending file as attachment
$attachmentFilePath = Mage::getBaseDir('media'). DS . 'contacts' . DS . $fileName;
if(file_exists($attachmentFilePath)){
$fileContents = file_get_contents($attachmentFilePath);
$attachment = $mailTemplate->getMail()->createAttachment($fileContents);
$attachment->filename = $fileName;
}
/**************************************************************/
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}
I created a contacts directory in medias with 777 rights
The contact form is correctly shown in my page, i can choose a file, but it isnt uploaded. In medias/contacts/ no file, and in my email i have a attached file called noname
Impossible to use it. Im sure i did something wrong but i cant find what exactly is wrong.
Im not a pro Magento admin, so if you can explain me in details that will be cool :)
Thanks all
i have tried recreating your scenario in my local installation and changed your contoller file uploader code with one of my working modules.
/**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts' . DS ;
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path, $_FILES['attachment']['contacts'] );
$newFilename = $uploader->getUploadedFileName();
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************/
This is working 100% correctly i have tested this for pdf also.
Please try changing once.
Replace
if(file_exists($attachmentFilePath)){
With this
if(file_exists($attachmentFilePath) && is_file($attachmentFilePath)){
Because file_exists results to TRUE if the file OR the directory exists. My email being sent out would send a blank "Mail Attachment" file because the file upload input on my contact form was optional.

How to create a category and add an image programatically

I've written a script that creates a category and adds a thumbnail image. It is inserted in the database but the thumbnail is not displayed.
When I upload from the backend it works fine.
This is my code.
<?php
require_once 'businessclasses.php';
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(1); // Mage_Core_Model_App::ADMIN_STORE_ID
$count = 0;
importRootCategories('us', '1/31/32', 4);
function importRootCategories($language, $path, $storeID)
{
$data = new getCSV();
$rows = $data->getRootCategories(); // Gets the list of root categories.
foreach($rows as $row) {
$categoryName = utf8_decode(iconv('ISO-8859-1','UTF-8',strip_tags(trim($row[$language])))); // Name of Category
if($language == "us") {
if($row[$language] == "")
$categoryName = utf8_decode(iconv('ISO-8859-1','UTF-8',strip_tags(trim($row["en"])))); // Name of Category
}
// Create category object
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeID); // 'US-Store' store is assigned to this category
$rootCategory['name'] = $categoryName;
$rootCategory['path'] = $path; // this is the catgeory path - 1 for root category
$rootCategory['display_mode'] = "PRODUCTS";
$rootCategory['include_in_menu'] = 1;
$rootCategory['is_active'] = 1;
$rootCategory['is_anchor'] = 1;
$rootCategory['thumbnail'] = _getCategoryImageFile($row['catimg'].'.jpg');
$category->addData($rootCategory);
try {
$category->save();
echo $rootCategoryId = $category->getId();
}
catch (Exception $e){
echo $e->getMessage();
}
}
}
function _getCategoryImageFile($filename)
{
$filePath = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS . $filename;
$fileUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'import/category/'. $filename;
$imageUrl=file_get_contents($imageUrl);
$file_handler=fopen($filePath,'w');
if(fwrite($file_handler,$fileUrl)==false){
Mage::log('ERROR: ', null,'error');
}
else{
Mage::log('Image Created Successfully', null, '');
}
fclose($file_handler);
return $filename;
}
?>