Programmatically add multiple images to a single product in magento - magento

The product id is given to which multiple images need to be added in magento.
$count = 0;
$imgArray = array($fpath.'configurable.png');
foreach ($imgArray as $image){
$imgUrl = _save_image( $image,$objectManager );
if ($count == 0){
$configProduct->addImageToMediaGallery( $imgUrl , $mediaAttribute, true, false );
}else {
$configProduct->addImageToMediaGallery( $imgUrl , null, true, false );
}
$count++;
}

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId); // Load product object
$mediaAttribute = array ('thumbnail','small_image','image');
$mediaDir = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList')->getPath('media');// Im Magento 2
$mediaDir = Mage::getBaseDir('media');// In Magento 1
//Case 1: When image files are alredy in your server
$fpath = 'product/images/';// path to your file
$count = 0;
$imgArray = array('image1.png','image2.png','image3.png','image4.png');
foreach ($imgArray as $image){
$imgUrl = _save_image( $fpath.$image,$objectManager,$mediaDir );// copies the file from your local storage to your-magento-root-path/pub/media
if ($count == 0){
$product->addImageToMediaGallery( $imgUrl , $mediaAttribute, true, false );
}else {
$product->addImageToMediaGallery( $imgUrl , null, true, false );
}
$count++;
}
function _save_image($img,$objectManager,$mediaDir) {
$imageFilename = basename($img);
$image_type = substr(strrchr($imageFilename,"."),1); //find the image extension
$filename = md5($img . strtotime('now')).'.'.$image_type; //give a new name, you can modify as per your requirement
if (!file_exists($mediaDir)) mkdir($mediaDir, 0777, true);
else chmod($mediaDir, 0777);
$filepath = $mediaDir . '/'. $filename; //path for temp storage folder: pub/media
file_put_contents($filepath, file_get_contents(trim($img))); //store the image from external url to the temp storage folder
return $filepath;
}
//Case 2: When you have to browse images from a form. (Then save into your server and then )
if(!empty($imageFile)){
$count = 0;
if (!file_exists($mediaDir)) mkdir($mediaDir, 0777, true);
else chmod($mediaDir, 0777);
foreach($imageFile['name'] as $k2=>$v2){
if($imageFile['error'][$k2] == 0 && file_exists($imageFile['tmp_name'][$k2])){
$ext[$k2] = pathinfo($imageFile['name'][$k2], PATHINFO_EXTENSION);
$filename[$k2] = md5(strtotime('now')).'.'.$ext[$k2];
$filepath[$k2] = $mediaDir .'/'. $filename[$k2];
$bin_string[$k2] = file_get_contents($imageFile['tmp_name'][$k2]);
file_put_contents($filepath[$k2], $bin_string[$k2]);
if ($count == 0) :
$product[$k]->addImageToMediaGallery( $filepath[$k2] , $mediaAttribute, true, false );
else :
$product[$k]->addImageToMediaGallery( $filepath[$k2] , null, true, false );
endif;
$count++;
}
}
}

The following code works for me.
https://www.pearlbells.co.uk/programmatically-add-multiple-images-magento-2/
if(sizeof($imgs) > 1) {
/* Assign additional images to existing products */
$product = $_objectManager->create('Magento\Catalog\Model\Product')->load($newProdId);
$productRepository = $_objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$productRepository->save($product);
for ( $i=1; $i<sizeof($imgs); $i++ ) {
echo 'Add Images :' . $prdbasepath.basename(trim($imgs[$i])) . PHP_EOL;
$image_directory = $prdbasepath.'data'.DS.basename(trim($imgs[$i]));
if (file_exists($image_directory) && getimagesize($image_directory)) {
echo 'File exists'.PHP_EOL;
$product->addImageToMediaGallery($image_directory, array('image', 'small_image', 'thumbnail'), false, false);
$product->save();
}
}
}

Related

Error 500 ajax-upload.php Uploading avatar

When I try to upload an avatar it is always loading and gives the error "
POST ajax-upload.php 500 (Internal Server Error) " in chrome inspector
Plugin installed Ultimate Membership Pro
Code of ajax-upload.php:
<?php
/*
* Upload files via Ajax
*/
require_once("../../../../wp-load.php");
// security layer
$uid = indeed_get_uid();
$access = true;
if ( !$uid ){
$hash = isset( $_COOKIE['ihcMedia'] ) ? $_COOKIE['ihcMedia'] : '';
if ( empty($hash) ){
$access = false;
}
$hash = esc_sql( $hash );
$exists = \Ihc_Db::doesMediaHashExists( $hash );
if ( !$exists ){
$access = false;
}
}
// end of security layer
if ( $access ){
if (isset($_FILES['avatar'])){
//========== handle avatar image
if ($_FILES['avatar']['type']=='image/png' || $_FILES['avatar']['type']=='image/gif' || $_FILES['avatar']['type']=='image/jpeg'){
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
$arr['id'] = media_handle_upload('avatar', 0);
if ($arr['id']){
$arr['url'] = wp_get_attachment_url($arr['id']);
$arr['secret'] = md5($arr['url']);
echo json_encode($arr);
} else {
echo '';
}
}
} else if (isset($_FILES['ihc_file'])){
//============= handle upload file
//debug
//file_put_contents( "upload_media.log", $_FILES['ihc_file']['type'], FILE_APPEND | LOCK_EX );
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
$arr['id'] = media_handle_upload('ihc_file', 0);
if ($arr['id']){
$arr['url'] = wp_get_attachment_url( $arr['id'] );
$arr['secret'] = md5($arr['url']);
}
$arr['name'] = $_FILES['ihc_file']['name'];
if (in_array($_FILES['ihc_file']['type'], array('image/gif','image/jpg','image/jpeg','image/png'))){
$arr['type'] = 'image';
} else {
$arr['type'] = 'other';
}
echo json_encode($arr);
}
else if (isset($_FILES['img'])){
//// upload account page banner
$cropImage = new Indeed\Ihc\CropImage();
echo $cropImage->saveImage($_FILES)
->getResponse();
}
else if (isset($_POST['imgUrl'])){
$cropImage = new Indeed\Ihc\CropImage();
if ( isset($_POST['customIdentificator']) && $_POST['customIdentificator']=='image' ){
$cropImage->setSaveUserMeta( false );
}
echo $cropImage->cropImage($_POST)
->getResponse();
}
}
Chrome inspector:
POST http://mysitename/wp-content/plugins/indeed-membership-
pro/public/ajax-upload.php 500 (Internal Server Error)
send # jquery.js?ver=1.12.4-wp:4
ajax # jquery.js?ver=1.12.4-wp:4
(anonymous) # croppic.js:281
dispatch # jquery.js?ver=1.12.4-wp:3
r.handle # jquery.js?ver=1.12.4-wp:3
11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111

DataBase Schema File (.sql file ) Download with laravel

Schenario :
1) suppose that i have a database called myDataBase
2) Assume that myDataBase have some tables like A,B,C,D
3) i have to download the schema of the table A,B from the database with name myDataBase
Hope you have done the migration of all the table of your project . If you are using a xampp server then goto http://localhost/phpmyadmin and select your database and then goto export tab on the top tab bar and simply export with go button
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlUserName = "root";
$mysqlPassword = "";
$mysqlHostName = "localhost";
$DbName = "ukkoteknik";
$backup_name = "mybackup.sql";
$tables = array("admin", "sample");
Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables, $backup_name=false );
function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false )
{
$mysqli = new mysqli($host,$user,$pass,$name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row())
{
$target_tables[] = $row[0];
}
if($tables !== false)
{
$target_tables = array_intersect( $target_tables, $tables);
}
foreach($target_tables as $table)
{
$result = $mysqli->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$mysqli->affected_rows;
$res = $mysqli->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0)
{
while($row = $result->fetch_row())
{ //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 )
{
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++)
{
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j]))
{
$content .= '"'.$row[$j].'"' ;
}
else
{
$content .= '""';
}
if ($j<($fields_amount-1))
{
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num)
{
$content .= ";";
}
else
{
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
//$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
$date = date("Y-m-d");
$backup_name = $backup_name ? $backup_name : $name.".$date.sql";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
//echo $content; exit;
}
?>

Magento export categories -> import with magmi

we need to change the categories of some products and it is easier for us to do this with a csv file.
Is there a way to export the categories in magmi format?
sku,categories
"abc","cat1/cat2;;cat5/cat6/cat1"
"bgb","cat1/cat2"
or is there maybe a small tool to manage the products in categories?
Edit:
this is the current code which is displaying the category names.
But I am trying to display the category path like this:
FirstCat/Tools/Screwdriver
But it is displaying like this:
FirstCat/Screwdriver/Tools
so the categoryid is not sorted.
<?php
error_reporting(E_ALL | E_STRICT);
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
Mage::app();
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('category_ids');
$products->addAttributeToSelect('sku');
$products->addAttributeToFilter('status', 1);//optional for only enabled products
$products->addAttributeToFilter('visibility', 4);//optional for products only visible in catalog and search
$fp = fopen('exports.csv', 'w');
$csvHeader = array("sku", "category_ids");
fputcsv( $fp, $csvHeader,",");
foreach ($products as $product){
$sku = $product->getSku();
$i = 2;
$len = count($product->getCategoryIds());
$str = "";
foreach ($product->getCategoryIds() as $id){
$category = Mage::getModel('catalog/category')->load($id);
$name = $category->getName();
$str .= $name;
if($i <= $len) {
$str = $str .= "/";
}
$i++;
}
fputcsv($fp, array($sku, $str), ",");
}
fclose($fp);
I use this code to export out categories. You can try to run it, don't forget to modify your path to your mage/app.php:
<?php
require_once('../yourpath/app/Mage.php');
Mage::app('admin');
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
Mage::register("isSecureArea", true);
function saveData($file, $data) {
$fh = fopen($file, 'w');
foreach ($data as $dataRow) {
fputcsva($fh, $dataRow);
}
fclose($fh);
return $this;
}
function fputcsva(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {
$str = '';
$escape_char = '\\';
foreach ($fields as $value) {
if (strpos($value, $delimiter) !== false ||
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] == $escape_char) {
$escaped = 1;
} else if (!$escaped && $value[$i] == $enclosure) {
$str2 .= $enclosure;
} else {
$escaped = 0;
}
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2 . $delimiter;
} else {
if (strlen($value)):
$str .= $enclosure . $value . $enclosure . $delimiter;
else:
$str .= $value . $delimiter;
endif;
}
}
$str = substr($str, 0, -1);
$str .= "\n";
return fwrite($handle, $str);
}
function geturl($connect, $value){
$id= $value;
if ($id) {
$sql = "SELECT value FROM magento.catalog_category_entity_url_key where entity_id=$id;";
$result = $connect->query($sql)->fetchObject();
} else {
return "";
}
return $result->value;
}
$modifiedarray = array();
$configpricearray=array();
$coreResource = Mage::getSingleton('core/resource');
$connect = $coreResource->getConnection('core_write');
$sql = "SELECT entity_id FROM catalog_category_entity;";
$category_row = $connect->query($sql);
$i=1;
$problematiccats=array(394,395,397,398);
$problematiccolumn=array('path','parent_id','level', 'position');
while ($row = $category_row->fetch()) {
$catid=$row['entity_id'];
echo "Category id: ".$catid.PHP_EOL;
if (in_array($catid,$problematiccats)): continue; endif;
$catsql="SELECT
ce.entity_id,
ce.parent_id,
ce.path,
ce.level,
ce.position,
ce.children_count,
ea.attribute_id,
ea.attribute_code,
CASE ea.backend_type
WHEN 'varchar' THEN ce_varchar.value
WHEN 'int' THEN IFNULL (eav_option.value,ce_int.value)
WHEN 'text' THEN ce_text.value
WHEN 'decimal' THEN ce_decimal.value
WHEN 'datetime' THEN ce_datetime.value
ELSE ea.backend_type
END AS value,
ea.is_required AS required
FROM catalog_category_entity AS ce
LEFT JOIN eav_attribute AS ea
ON ce.entity_type_id = ea.entity_type_id
LEFT JOIN catalog_category_entity_varchar AS ce_varchar
ON ce.entity_id = ce_varchar.entity_id
AND ea.attribute_id = ce_varchar.attribute_id
AND ea.backend_type = 'varchar'
AND ce_varchar.store_id = 0
LEFT JOIN catalog_category_entity_int AS ce_int
ON ce.entity_id = ce_int.entity_id
AND ea.attribute_id = ce_int.attribute_id
AND ea.backend_type = 'int'
AND ce_int.store_id = 0
LEFT JOIN catalog_category_entity_text AS ce_text
ON ce.entity_id = ce_text.entity_id
AND ea.attribute_id = ce_text.attribute_id
AND ea.backend_type = 'text'
AND ce_text.store_id = 0
LEFT JOIN catalog_category_entity_decimal AS ce_decimal
ON ce.entity_id = ce_decimal.entity_id
AND ea.attribute_id = ce_decimal.attribute_id
AND ea.backend_type = 'decimal'
AND ce_decimal.store_id = 0
LEFT JOIN catalog_category_entity_datetime AS ce_datetime
ON ce.entity_id = ce_datetime.entity_id
AND ea.attribute_id = ce_datetime.attribute_id
AND ea.backend_type = 'datetime'
LEFT JOIN eav_attribute_option_value as eav_option
ON eav_option.option_id=ce_int.value
AND eav_option.store_id=0
WHERE ce.entity_id = '$catid';";
$category_info = $connect->query($catsql);
$csvrow=array();
if ($i==1): $csvrow['entity']='entity_id';$csvrow['parent']='parent_id'; $csvrow['path']='path';
$csvrow['level']='level';
$csvrow['position']='position';
$csvrow['children_count']='children_count';endif;
while ($catrow = $category_info->fetch()) {
if (in_array($catrow['attribute_code'],$problematiccolumn)): continue; endif;
if ($i==1):
$csvrow[]=$catrow['attribute_code'];
else:
$csvrow['entity']=$catrow['entity_id'];
$csvrow['parent']=$catrow['parent_id'];
$csvrow['path']=$catrow['path'];
$csvrow['level']=$catrow['level'];
$csvrow['position']=$catrow['position'];
$csvrow['children_count']=$catrow['children_count'];
$csvrow[$catrow['attribute_code']]=($catrow['value']?$catrow['value']:"");
if ($catrow['attribute_code']=="url_key"):
if (strlen($catrow['url_key'])<3):
$csvrow['url_key']=geturl($connect,$catid);
endif;
endif;
endif;
}
$csv[]=$csvrow;
$i++;
}
$file_path = 'categoryexport.csv';
try {
saveData($file_path, $csv);
} catch (Exception $e) {
echo "[ERROR] Creating sale report file: " . $e->getMessage() . PHP_EOL;
}
In this solution the db was'n in very well state, so the url needs to grabbed separately, you can remove that part if not necessary for you.
I used this on EE 1.13.0.2
You can run it from the shell.
Now here is my solution. Its displaying the csv in the browser. After that you can reimport with magmi
<?php
error_reporting(E_ALL | E_STRICT);
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
Mage::app();
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('category_ids');
$products->addAttributeToSelect('sku');
$products->addAttributeToFilter('status', 1);//optional for only enabled products
$products->addAttributeToFilter('visibility', 4);//optional for products only visible in catalog and search
foreach ($products as $product){
$sku = $product->getSku();
echo $sku.",";
$i = 2;
$anzahl = count($product->getCategoryIds());
foreach ($product->getCategoryIds() as $id){
$category = Mage::getModel('catalog/category')->load($id);
$path = $category->getPath();
$ids = explode("/", $path);
$name = "";
$i2 = 2;
$anzahl2 = count($ids);
foreach($ids as $id_2) {
$category = Mage::getModel('catalog/category')->load($id_2);
$name .= $category->getName();
echo $category->getName();
if($i2 <= $anzahl2) {
$name .= "/";
echo "/";
}
$i2++;
}
if($i <= $anzahl) {
$name .= ";;";
echo ";;";
}
$i++;
}
echo "<br />";
}

joomla pagination shows same result on every page

I have page of articles with more than 5 results. 5 results are displayed per page. Pagination shows up. When I go to different pages however, every page has the same 5 results.
My getItems():
function getItems()
{
$params = $this->getState()->get('params');
$limit = $this->getState('list.limit');
// 5
if ($this->_articles === null && $category = $this->getCategory()) {
$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
$model->setState('params', JFactory::getApplication()->getParams());
$model->setState('filter.category_id', $category->id);
$model->setState('filter.published', $this->getState('filter.published'));
$model->setState('filter.access', $this->getState('filter.access'));
$model->setState('filter.language', $this->getState('filter.language'));
$model->setState('list.ordering', $this->_buildContentOrderBy());
$model->setState('list.start', $this->getState('list.start'));
$model->setState('list.limit', $limit);
$model->setState('list.direction', $this->getState('list.direction'));
$model->setState('list.filter', $this->getState('list.filter'));
// filter.subcategories indicates whether to include articles from subcategories in the list or blog
$model->setState('filter.subcategories', $this->getState('filter.subcategories'));
$model->setState('filter.max_category_levels', $this->setState('filter.max_category_levels'));
$model->setState('list.links', $this->getState('list.links'));
if ($limit >= 0) {
$this->_articles = $model->getItems();
if ($this->_articles === false) {
$this->setError($model->getError());
}
}
else {
$this->_articles=array();
}
$this->_pagination = $model->getPagination();
}
$filterResult = null;
return $this->_articles;
}
My populate state:
protected function populateState($ordering = null, $direction = null)
{
// Initiliase variables.
$app = JFactory::getApplication('site');
$pk = JRequest::getInt('id');
$this->setState('category.id', $pk);
// Load the parameters. Merge Global and Menu Item params into new object
$params = $app->getParams();
$menuParams = new JRegistry;
if ($menu = $app->getMenu()->getActive()) {
$menuParams->loadString($menu->params);
}
$mergedParams = clone $menuParams;
$mergedParams->merge($params);
$this->setState('params', $mergedParams);
$user = JFactory::getUser();
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
$groups = implode(',', $user->getAuthorisedViewLevels());
if ((!$user->authorise('core.edit.state', 'com_content')) && (!$user->authorise('core.edit', 'com_content'))){
// limit to published for people who can't edit or edit.state.
$this->setState('filter.published', 1);
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$this->setState('filter.created_by', $this->getUserId(JRequest::getVar('author')));
}
// Filter by start and end dates.
$nullDate = $db->Quote($db->getNullDate());
$nowDate = $db->Quote(JFactory::getDate()->toMySQL());
$query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')');
$query->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$query->where('(a.created_by = "' . $this->getUserId(JRequest::getVar('author')) . '")');
}
}
// process show_noauth parameter
if (!$params->get('show_noauth')) {
$this->setState('filter.access', true);
}
else {
$this->setState('filter.access', false);
}
// Optional filter text
$this->setState('list.filter', JRequest::getString('filter-search'));
// filter.order
$itemid = JRequest::getInt('id', 0) . ':' . JRequest::getInt('Itemid', 0);
$orderCol = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order', 'filter_order', '', 'string');
if (!in_array($orderCol, $this->filter_fields)) {
$orderCol = 'a.ordering';
}
$this->setState('list.ordering', $orderCol);
$listOrder = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order_Dir',
'filter_order_Dir', '', 'cmd');
if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', ''))) {
$listOrder = 'ASC';
}
$this->setState('list.direction', $listOrder);
//$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
// set limit for query. If list, use parameter. If blog, add blog parameters for limit.
if ((JRequest::getCmd('layout') == 'blog') || $params->get('layout_type') == 'blog') {
$limit = $params->get('num_leading_articles') + $params->get('num_intro_articles') + $params->get('num_links');
$this->setState('list.links', $params->get('num_links'));
}
else {
$limit = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.limit', 'limit', $params->get('display_num'));
}
$this->setState('list.limit', $limit);
// set the depth of the category query based on parameter
$showSubcategories = $params->get('show_subcategory_content', '0');
if ($showSubcategories) {
$this->setState('filter.max_category_levels', $params->get('show_subcategory_content', '1'));
$this->setState('filter.subcategories', true);
}
$this->setState('filter.language',$app->getLanguageFilter());
$this->setState('layout', JRequest::getCmd('layout'));
}
My display function de view.html.php
function display($tpl = null)
{
$app = JFactory::getApplication();
$user = JFactory::getUser();
// Get some data from the models
$state = $this->get('State');
$params = $state->params;
$items = $this->get('Items');
$contactId = JRequest::getVar('author');
if($contactId){
$this->setUserId($contactId);
$this->setContactName($this->userId);
}
$category = $this->get('Category');
$children = $this->get('Children');
$parent = $this->get('Parent');
$pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
JError::raiseError(500, implode("\n", $errors));
return false;
}
if ($category == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
if ($parent == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
// Setup the category parameters.
$cparams = $category->getParams();
$category->params = clone($params);
$category->params->merge($cparams);
// Check whether category access level allows access.
$user = JFactory::getUser();
$groups = $user->getAuthorisedViewLevels();
if (!in_array($category->access, $groups)) {
return JError::raiseError(403, JText::_("JERROR_ALERTNOAUTHOR"));
}
// PREPARE THE DATA
// Get the metrics for the structural page layout.
$numLeading = $params->def('num_leading_articles', 1);
$numIntro = $params->def('num_intro_articles', 4);
$numLinks = $params->def('num_links', 4);
// Compute the article slugs and prepare introtext (runs content plugins).
for ($i = 0, $n = count($items); $i < $n; $i++)
{
$item = &$items[$i];
$item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id;
// No link for ROOT category
if ($item->parent_alias == 'root') {
$item->parent_slug = null;
}
$item->event = new stdClass();
$dispatcher = JDispatcher::getInstance();
// Ignore content plugins on links.
if ($i < $numLeading + $numIntro) {
$item->introtext = JHtml::_('content.prepare', $item->introtext);
$results = $dispatcher->trigger('onContentAfterTitle', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayTitle = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentBeforeDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->beforeDisplayContent = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentAfterDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayContent = trim(implode("\n", $results));
}
}
// Check for layout override only if this is not the active menu item
// If it is the active menu item, then the view and category id will match
$active = $app->getMenu()->getActive();
if ((!$active) || ((strpos($active->link, 'view=category') === false) || (strpos($active->link, '&id=' . (string) $category->id) === false))) {
// Get the layout from the merged category params
if ($layout = $category->params->get('category_layout')) {
$this->setLayout($layout);
}
}
// At this point, we are in a menu item, so we don't override the layout
elseif (isset($active->query['layout'])) {
// We need to set the layout from the query in case this is an alternative menu item (with an alternative layout)
$this->setLayout($active->query['layout']);
}
// For blog layouts, preprocess the breakdown of leading, intro and linked articles.
// This makes it much easier for the designer to just interrogate the arrays.
if (($params->get('layout_type') == 'blog') || ($this->getLayout() == 'blog')) {
$max = count($items);
// The first group is the leading articles.
$limit = $numLeading;
for ($i = 0; $i < $limit && $i < $max; $i++) {
$this->lead_items[$i] = &$items[$i];
}
// The second group is the intro articles.
$limit = $numLeading + $numIntro;
// Order articles across, then down (or single column mode)
for ($i = $numLeading; $i < $limit && $i < $max; $i++) {
$this->intro_items[$i] = &$items[$i];
}
$this->columns = max(1, $params->def('num_columns', 1));
$order = $params->def('multi_column_order', 1);
if ($order == 0 && $this->columns > 1) {
// call order down helper
$this->intro_items = ContentHelperQuery::orderDownColumns($this->intro_items, $this->columns);
}
$limit = $numLeading + $numIntro + $numLinks;
// The remainder are the links.
for ($i = $numLeading + $numIntro; $i < $limit && $i < $max;$i++)
{
$this->link_items[$i] = &$items[$i];
}
}
$children = array($category->id => $children);
//Escape strings for HTML output
$this->pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
$this->assign('maxLevel', $params->get('maxLevel', -1));
$this->assignRef('state', $state);
$this->assignRef('items', $items);
$this->assignRef('category', $category);
$this->assignRef('children', $children);
$this->assignRef('params', $params);
$this->assignRef('parent', $parent);
$this->assignRef('pagination', $pagination);
$this->assignRef('user', $user);
$this->_prepareDocument();
parent::display($tpl);
}
If i print the contents of $pagination in the view.html.php here:
$this->_prepareDocument();
echo '<pre>'; print_r($pagination); exit();
parent::display($tpl);
I get the following results:
In my template file I echo the pagination:
<?php echo $this->pagination->getPagesLinks(); ?>
By the way, clicking on 'next' does change the url into ...?start=5.
This line in populateState is commented out
$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
Uncomment it change it tot get the "start" parameter:
$this->setState('list.start', JRequest::getVar('start', 0, '', 'int'));

error reading db in joomla

While i run a component i am getting 500 - An error has occurred error reading db in joomla.
My configuration file is perfect.
I don't know what else to change..
Any guidance will be helpful
Thanks in advance...
//No direct acesss
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class DealsModelDeals extends JModel {
function getDeals(){
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
if ($deals === null)
JError::raiseError(500, 'Error reading db');
return $deals;
}
function getDeal($id){
$query = ' SELECT * FROM #__todaysdeal '. ' WHERE id = '.$id;
$db = $this->getDBO();
$db->setQuery($query);
$deal = $db->loadObject();
if ($deal === null)
JError::raiseError(500, 'Deal with ID: '.$id.' not found.');
else
return $deal;
}
/**
* Method that returns an empty greeting with id 0
*
* #access public
*/
function getNewDeal(){
$dealTableRow =& $this->getTable('deals');
$dealTableRow->id=0;
$dealTableRow->clientName='';
return $dealTableRow;
}
/**
* Method to store a greeting in the DB
*
* #access public
*/
function saveDeal($deal)
{
//Parameter not necessary because our model is named DealsModelDeals (used to ilustrate that you can specify an alternative name to the JTable extending class)
$dealTableRow =& $this->getTable('deals');
//print_r($dealTableRow);
//print_r($_FILES); exit;
// Bind the form fields to the todaysdeal table
if (!$dealTableRow->bind($deal)) {
JError::raiseError(500, 'Error binding data');
}
// Make sure the deal record is valid
if (!$dealTableRow->check()) {
JError::raiseError(500, 'Invalid data');
}
// Insert/update this record in the db
if (!$dealTableRow->store()) {
$errorMessage = $dealTableRow->getError();
JError::raiseError(500, 'Error binding data: '.$errorMessage);
}
$id = $dealTableRow->id;
if(!empty($_FILES['dealImage']))
{
$file = $_FILES['dealImage'];
$id = $dealTableRow->id;
if ((($_FILES["dealImage"]["type"] == "image/gif") || ($_FILES["dealImage"]["type"] == "image/jpeg") || ($_FILES["dealImage"]["type"] == "image/pjpeg")) && ($_FILES["dealImage"]["size"] < 150000))
{
if ($_FILES["dealImage"]["error"] > 0)
{
echo "Return Code: " . $_FILES["dealImage"]["error"] . "<br />";
}
else
{
if (file_exists("components/com_deals/dealImages/" . $_FILES["dealImage"]["name"])) {
$_FILES["dealImage"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["dealImage"]["tmp_name"], "components/com_deals/dealImages/" .$id."_".$_FILES["dealImage"]["name"]);
echo "Stored in: " . "dealImages/" . $_FILES["dealImage"]["name"];
}
}
}
else
{
}
}
$dealImage = $_FILES['dealImage']['name'];
$dealImage .= (!empty($_FILES['dealImage']['name'])) ? ' ' . $_FILES['dealImage']['name'] : '';
$query = "UPDATE #__todaysdeal SET dealImage='".$id."_".$_FILES['dealImage']['name']."' WHERE id='".$id."'";
$db = $this->getDBO();
$db->setQuery($query);
$db->query();
//If we get here and with no raiseErrors, then everythign went well
}
function deleteDeals($arrayIDs)
{
$query = "DELETE FROM #__todaysdeal WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error deleting Deals: '.$errorMessage);
}
}
function dealsUploadPhoto($file, $id)
{
//UPLOAD FILE
$config = & JComponentHelper::getParams('com_deals');
$allowed = array('image/pjpeg', 'image/jpeg', 'image/jpg', 'image/png', 'image/x-png', 'image/gif', 'image/ico', 'image/x-icon');
$pwidth = $config->get('pwidth');
$pheight = $config->get('pheight');
$maxsize = $config->get('maxsize');
if($file['size'] > 0 && ($file['size'] / 1024 < $maxsize)){
if(!file_exists(JPATH_SITE . DS. 'images' . DS . 'deals'))
{
if(mkdir(JPATH_SITE . DS . 'images' . DS . 'deals')) {
JPath::setPermissions(JPATH_SITE . DS . 'images' . DS . 'deals', '0777');
if(file_exists(JPATH_SITE . DS . 'images' . DS . 'index.html')) {
copy(JPATH_SITE . DS . 'images' . DS . 'index.html', JPATH_SITE . DS . 'images' . DS . 'deals/index.html');
}
}
}
if($file['error'] != 0){
tpJobsMsgAlert('Upload file photo error.');
exit ();
}
if($file['size'] == 0){
$file = null;
}
if(!in_array($file['type'], $allowed)) {
$file = null;
}
if ($file != null){
$dest = JPATH_SITE.DS.'images'.DS.'deals'.DS.$id.'.jpg';
if(file_exists($dest))
{
$del = unlink($dest);
}
$soure = $file['tmp_name'];
jimport('joomla.filesystem.file');
$uploaded = JFile::upload($soure,$dest);
$fileAtr = getimagesize($dest);
$widthOri = $fileAtr[0];
$heightOri = $fileAtr[1];
$type = $fileAtr['mime'];
$img = false;
switch ($type)
{
case 'image/jpeg':
case 'image/jpg':
case 'image/pjpeg':
$img = imagecreatefromjpeg($dest);
break;
case 'image/ico':
$img = imagecreatefromico($dest);
break;
case 'image/x-png':
case 'image/png':
$img = imagecreatefrompng($dest);
break;
case 'image/gif':
$img = imagecreatefromgif($dest);
break;
}
if(!$img)
{
return false;
}
$curr = #getimagesize($dest);
$perc_w = $pwidth / $widthOri;
$perc_h = $pheight / $heightOri;
if(($widthOri<$pwidth) && ($heightOri<$height))
{
return;
}
if($perc_h > $perc_w)
{
$pwidth = $pwidth;
$pheight = round($heightOri * $perc_w);
}
else
{
$pheight = $pheight;
$pwidth = round($widthOri * $perc_h);
}
$nwimg = imagecreatetruecolor($pwidth, $pheight);
imagecopyresampled($nwimg, $img, 0, 0, 0, 0, $pwidth, $pheight, $widthOri, $heightOri);
imagejpeg($nwimg, $dest, 100);
imagedestroy($nwimg);
imagedestroy($img);
}
}else{
if($file['size'] / 1024 > $maxsize){
dealsMsgAlert('Size of file photo is too big. Maximum size".$maxsize." KB');
exit ();
}
}
}
function dealsMsgAlert($msg)
{
if (!headers_sent())
{
while(#ob_end_clean());
ob_start();
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
$out = ob_get_contents();
ob_end_clean();
echo $out;
exit();
}
echo "<script> alert('".$msg."'); window.history.go(-1); </script>\n";
exit();
}
}
?>
The problem that causes the red screen with 500 Error is happening because you are raising an exception if the requested quote is does not exist. You should not use JError::raiseError().
Use one of the following instead:
// This will set error to the model. You can get the errors from
// the model by your controller $model->getErrors() and output them to the screen.
$this->setError('ERROR MESSAGE GOES HERE');
OR
// This will output errors to the screen right the way
JFactory::getApplication()->enqueueMessage('ERROR MESSAGE GOES HERE', 'message');
Model already has _db property, you do not need to get db into variable. You can access it like this $this->_db. You can read about Joomla Model class here.
Also within your model you are using
$db = $this->getDBO();
$db->setQuery('SELECT * from #__todaysdeal');
$deals = $db->loadObjectList();
Model has simplified method to load list of object, like so
$deals =& $this->_getList('SELECT * from #__todaysdeal');

Resources