Can't get image out with appended numbering - CodeIgniter - image

its a silly question but I'm really bad in escaping quotes :/.
I'm using the table class to generate a table of products, and in that table each row has an image to be displayed for that product. The images are stored using their product_id as a name with an appended "_x" because there's more than one image per product, so an example of an image name is 193_1.
This is how I'm generating my rows for the table:
$table_row = array();
foreach ($r->result() as $p)
{
$table_row = NULL;
$table_row[] = "<img src='http://localhost/CI/photos/$p->product_id\"1\".jpg' height='150' width='150'/>";
$table_row[] = $p->product_id;
$table_row[] = $p->title;
$table_row[] = $p->description;
$table_row[] = $p->price;
$table_row[] = $p->stock;
$this->table->add_row($table_row);
}
But the image won't show, even when I've escaped the '1'. I only want to display the first image as that is the main one, so that's why I've hard-coded the number. Could someone please help? I've tried multiple ways i.e.
"<img src='http://localhost/CI/photos/$p->product_id '1' .jpg' height='150' width='150'/>"
"<img src='http://localhost/CodeIgniter/photos/<?php echo $p->product_id; ?>1.jpg' height='150' width='150'/>";
But the image still doesn't show. The table is being generated in my Controller which is a PHP file so I don't really think I need to use php tags

"<img src='http://localhost/CodeIgniter/images/" . $product->product_id . "_1.jpg' height='100' width='100'/>";

Related

Opencart 1.5.5.1 categories images on homepage

I've add module "categories" to homepage, and now I see categories list with numer of products on homepage but can't see category thumbs.
in file: /public_html/catalog/view/theme/MY-THEME/template/module/category.tpl I found around line 10:
<?php echo $category['name']; ?>
and I think sommewhere there I also should add something like: category['thumb'] to display image before category name but do I have to add something in controller files, I soppouse yes but need help here.
I thing i should define $category['thumb'] in controller but how to do this?
You're correct in saying that you need to edit the controller file for this module, you need to add the model that gets the image for that category as well as get the image for any child categories. So there are two edits you need to make, first to the controller file
Open the catalog/controller/module/category.php & find this line:
$this->load->model('catalog/product');
Now you need to add the model so that you can get the image data from the DB, add this line below it:
$this->load->model('tool/image');
Now find this line, it will be in the foreach loop:
$children = $this->model_catalog_category>getCategories($category['category_id']);
Add the following above the line:
$category_info = $this->model_catalog_category>getCategory($category['category_id']);
if ($category_info['image']) {
$image = $category_info['image'];
} else {
$image = '';
}
You also need to do this for the child categories, find this line in the next foreach loop:
$product_total = $this->model_catalog_product->getTotalProducts($data);
Add this directly below it:
$child_info = $this->model_catalog_category>getCategory($child['category_id']);
if ($child_info['image']) {
$child_image = $child_info['image'];
} else {
$child_image = '';
}
At the moment we now have two variables that contain the image paths: $image and $child_image, these need to be passed to the template file, you can do so by editing the two arrays that are created. We'll do the child array first as that is almost directly below the last edit you made. Find this line in the children_data array:
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
Add a comma to the end of the line and paste this line directly below it:
'image' => $child_image
Now we add the image to the $category array, find this line and add a comma to the end as with the last step:
'href' => $this->url->link('product/category', 'path=' . $category['category_id'])
The next step is obvious now, add the following line directly below it:
'image' => $image
Now you should note that the template file can access a new variable $image when in the foreach loops. I'll leave the rest to you as you'd know how and where you'd like to display the image. The code below will generate an image if it's used in the foreach loop of either the Category:
<img src="<?php echo $category['image']; ?>
Or this can be used for a child category:
<img src="<?php echo $child['image']; ?>

jqGrid How to use EditUrl

I'm using jqGrid to maintain a database in MySQL using jSON data. I'm able to display the data in the grid but when I try to add or edit a data row through the modal form I get a message saying "Url is not set". But what is the editurl suppose to contain? mysql insert statements? I'm using the grid's predefined add and edit functions.
Also, if you take a look at the trirand demo page under Manipulating then under Grid Data. They specify their url as url:'server.php?q=2' and their editurl:"someurl.php" They never say what the someurl.php contains. This is where I get lost and I can't find a resource to give me any hints as to what is suppose to be in the editurl php file.
Thanks for any advice.
UPDATE:
Code in my editurl php file: I put the POST values from the col model in variables. I only need insert and update statements in the switch statement. Take a look at my insert statement to see which one I should be using. I also have to make you aware that I'm not listing all the columns in the database but I'm listing all the columns that the user sees in the grid. The first insert statement is commented and it states the columns that the values are suppose to be inserted based on their order. The second insert statement is following the order that is in the database. Where you see ' ' are the columns that I didn't want to display to the data grid for the user to see because that information wasn't relevant.
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "**********";
$dbname = "codes";
// connect to the database
$mysql_connect($dbhost, $dbuser, $dbpass) or die("Connection Error: " . mysql_error());
mysql_select_db($dbname) or die("Error conecting to db.");
$div = $_POST['div_id'];
$l2 = $_POST['l2_id'];
$l1l2 = $_POST['l1l2_id'];
$l1l3 = $_POST['l1l3_id'];
$l2l3 = $_POST['l2l3_id'];
$beg = $_POST['exec_beg'];
$end = $_POST['exec_end'];
$csa = $_POST['csa_id'];
$area = $_POST['area_id'];
$areadesc = $_POST['area_desc'];
$shortdesc = $_POST['short_desc'];
$longdesc = $_POST['long_desc'];
$enabled = $_POST['avail_ind'];
switch($_POST['oper'])
{
case "add":
$query = "INSERT INTO divcodes values ($div,'',$l1l2,$l2,$l1l3,$l2l3,$beg,$end,'',''$csa,$area,$areadesc,$shortdesc,$longdesc,$enabled,'','','','','',''";
$run = mysql_query($query);
break;
case "edit":
//do mysql update statement here
break;
}
When I set the editurl to my php file and I try to add new row of data to the grid it gives me internal server error 500. I don't know how to debug it any further and the error 500 is such a general error.
I thought that since I was using the predefined operations of the grid (add/edit) that the grid would just know to perform an insert or update statement into my database but it looks like that's not the case?
UPDATE TAKE 2: I changed the syntax to use the mysqli extension. Once I restructured my insert statements I stopped getting the 'Internal Server Error Code 500'. When I click add new record then fill in test data then click on submit the modal window disappears like the data has been added to the grid. But no where in the grid can I find the data (maybe the grid is not reloading with the new data). I checked phpmyadmin and the new row is no where to be found. When I edit an existing row and click submit the dialog box stays open but I'm not getting the error 500 which is a relief.
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "**********";
$dbname = "codes";
// connect to the database
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Connection Error: " . mysql_error());
mysqli_select_db($conn,$dbname) or die("Error conecting to db.");
$div = $_POST['div_id'];
$l2 = $_POST['l2_id'];
$l1l2 = $_POST['l1l2_id'];
$l1l3 = $_POST['l1l3_id'];
$l2l3 = $_POST['l2l3_id'];
$beg = $_POST['exec_beg'];
$end = $_POST['exec_end'];
$csa = $_POST['csa_id'];
$area = $_POST['area_id'];
$areadesc = $_POST['area_desc'];
$shortdesc = $_POST['short_desc'];
$longdesc = $_POST['long_desc'];
$enabled = $_POST['avail_ind'];
switch($_POST['oper'])
{
case "add":
$query = "INSERT INTO divcodes (div_id,l1l2_id,l2_id,l1l3_id,l2l3_id,exec_beg,exec_end,csa_id,area_id,area_desc,short_desc,long_desc,avail_ind) values ($div,$l1l2,$l2,$l1l3,$l2l3,$beg,$end,$csa,$area,$areadesc,$shortdesc,$longdesc,$enabled)";
mysqli_query($conn,$query);
break;
case "edit":
$query = "UPDATE divcodes SET div_id=$div,l1l2_id=$l2,l2_id=$l1l2,l1l3_id=$l2l3,l2l3_id=$l2l3,exec_beg=$beg,exec_end=$end,csa_id=$csa,area_id=$area,area_desc=$areadesc,short_desc=$shortdesc,long_desc=$longdesc,avail_ind=$enabled";
mysqli_query($conn,$query);
break;
}
?>
The editurl is the PHP file that will do your INSERTS, UPDATES and DELETES.
There are several parameters passed to this file including the parameter: oper which will be either add, edit or del depending on which operation you did.
In your PHP file (the editurl file) I would just do a switch:
switch ($_POST["oper"]) {
case "add":
// do mysql insert statement here
break;
case "edit":
// do mysql update statement here
break;
case "del":
// do mysql delete statement here
break;
}
Also passed to that file will be all of your data from that row in name:value pairs, just like the oper parameter. The name will be the index property you defined in your colModel array when you setup your grid.
So if you had a column (from the colModel) that looked like:
{
name: 'name1',
index: 'name1',
width: 95,
align: "center",
hidden: false
}
In your editurl PHP file, you can access that column's value to build your queries above by using:
$_POST["name1"]
Hope this helps and let me know if you have any further questions. I struggled with this part of jQGrid just like you are so I know the pain!! lol
UPDATE
Your MySQL Insert statement is incorrect. You do not need to include every column in that exists in your table, just the ones that are required (the columns that can't be null).
For instance, I have a table (tableName) with three columns:
ID (required, not null)
Name (required, not null)
Phone (not required)
If I want to perform an insert onto this table, but I don't want to insert anything into the Phone column, my Insert statement would look like:
INSERT INTO tableName (ID, Name) VALUES (123, "Frank")
On the left side of VALUES is where you specify which columns you will be inserting into. On the right side of VALUES are the actual values we will be inserting.
Here is a simple, helpful link on MySQL syntax: http://www.w3schools.com/php/php_mysql_insert.asp
As you can see, in that first example on that link, they don't specify which columns, meaning they will be inserting data into ALL columns. In your case, that is not what you want, so I would check out their second example, which does specify the columns you are inserting into.

steps to import images with a product

What are the steps to import a product with images. I mean - the images, precisely.
So I have this code now:
protected function _getImages($product)
{
$importImagesDirectory = Mage::getBaseDir()."/".Mage::getStoreConfig('xmlimport/product/import_images_dir');
if(file_exists($importImagesDirectory))
{
$addImage['sku'] = (string)$product['PK_Produkt'];
$addImage['_media_image'] = $importImagesDirectory . $this->_getPresentationAttributeValue($product, '#Art="Bild" and #Rang="1"');
$addImage['_media_attribute_id'] = Mage::getSingleton('catalog/product')->getResource()->getAttribute('media_gallery')->getAttributeId();
$addImage['_media_is_disabled'] = 0;
$addImage['_media_position'] = 1;
// the following 4 lines are just acquiring string values - the name of the picture
$addImage['_media_lable'] = $this->_getPresentationAttributeValue($product, '#Art="Bild" and #Rang="1"');
$addImage['image'] = $this->_getPresentationAttributeValue($product, '#Art="Bild" and #Rang="1"');;
$addImage['small_image'] = $this->_getPresentationAttributeValue($product, '#Art="Bild" and #Rang="1"');;
$addImage['thumbnail'] = $this->_getPresentationAttributeValue($product, '#Art="Bild" and #Rang="1"');;
}
else Mage::log('Error! Image with name: ' . $importImagesDirectory . ' does not exist! ', null, 'error_image.log', true);
return $addImage;
}
So this array is being merged with the array containing the product information, that is being imported. Now, I was said that the function should also move the images from my media/import/ folder to somewhere catalog/product/ folder, because Magento looks up for images in that folder. Anf if I just import the information, but don't move the images - then no effect (which actually happens right now).
So I am asking, how does that work, is there a function from the API to make this "movement", is that the correct procedure?
As per this answer you need to use addImageToMediaGallery.
You need to have an instance of a catalog/product object. That should be easy $product = Mage::getModel('catalog/product'); and then you need to load its data from the DB for example $product->load($id);.
$product->addImageToMediaGallery($filePath, $imageType, false);
Magento stores product files in media/catalog/product/X/Y/XYfilename.ext where X and Y are the first letters of the filename. So Magento creates two levels of subfolders based on the first two letters in the filename. This logic is not present directly in addImageToMediaGallery, it's in Mage_Catalog_Model_Product_Attribute_Backend_Media::addImage().
magento_root: app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php

simplepie: use my own thumbnail per feed in a multifeed page

I've been looking everywhere but haven't found the answer to the question: How can I use my own thumbnail per feed in a multifeed page? If I've overlooked the answer it would be due to the wrong search keys for which i apologize in advance.
I've got the following code so far (which is not much):
<?php
include_once('autoloader.php');
include_once('idn/idna_convert.class.php');
date_default_timezone_set('Europe/Amsterdam');
setlocale(LC_TIME, 'nld_nld');
$feed = new SimplePie();
$urls = (array(
'http://myfeedurla.com' => 'descriptiona',
'http://myfeedurlb.com' => 'descriptionb',
'http://myfeedurlc.com' => 'descriptionc'
));
$feed->set_feed_url(array_keys($urls)); // this should get parse only the URLS
$feed->set_cache_location('cache/');
$feed->init();
$feed->handle_content_type();
?>
// As from here I'm using the standard simplepie code to show multiple feeds and order them by day
<?php
// Set up some variables we'll use.
$stored_date = '';
$list_open = false;
// Go through all of the items in the feed
foreach ($feed->get_items() as $item)
{
// What is the date of the current feed item?
$item_date = $item->get_date('M jS');
// Is the item's date the same as what is already stored?
// - Yes? Don't display it again because we've already displayed it for this date.
// - No? So we have something different. We should display that.
if ($stored_date != $item_date)
{
// If there was already a list open from a previous iteration of the loop, close it
if ($list_open)
{
echo '</ol>' . "\r\n";
}
// Since they're different, let's replace the old stored date with the new one
$stored_date = $item_date;
// Display it on the page, and start a new list
echo '<h1>' . $item->get_local_date('%A %d %B %Y') . '</h1><hr>' . "\r\n";
echo '<ol>' . "\r\n";
// Let the next loop know that a list is already open, so that it will know to close it.
$list_open = true;
}
// Display the feed item however you want...
echo '<li>' . $item->get_local_date('%H:%M') . ' | <h4>' . $item->get_title() . '</h4></li>' . "\r\n";
}
?>
Somewhere in the HTML I want to add the 'img scr=" . . "' etc. And there it should only refer to an image by the name 'descriptiona'.png respectively 'descriptionb'.png etc, per feed. Is this possible? And if yes, how?
If I should be more clear, pls don't hesitate to ask. Thanks in advance for the help!
Best regards,
Ok, so far I have one solution :) I use the title of the respective feeds in the img filename. I've added the following code:
<img src="images/' . $item->get_feed()->get_title() . '.png" width="12" height="12" />
Now I only hope that feeds won't use / or something in their titles... If someone has a better way of doing this, eg. by being able to add a personal title per feed, that would be very welcome.

PHP - How to accomplish this if?

I am creating an order cart.
On the page that displays the cart, it checks if a value stored in the session $order corresponds with an id of a row in a mysql table. If this match exists, then the corresponding row is returned.
Within this process, I am trying to retrieve the quantity value stored in the session $quantity that corresponds to the id of the row in the table.
Each value in $order and $quantityis assigned a name, which is the id of the item they were added from.
This is the code that adds the order to the cart:
if (isset($_POST['action']) and $_POST['action'] == 'Order')
{
// Add item to the end of the $_SESSION['order'] array
$_SESSION['order'][$_POST['id']] = $_POST['id'];
$_SESSION['quantity'][$_POST['id']] = $_POST['quantity'];
header('Location: .');
exit();
}
This is the code on the cart page:
foreach ($order as $item)
foreach ($quantity as $amount)
{
mysql_data_seek( $productsSql, 0); //<- this line, to reset the pointer for every EACH.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
if ($item == $itId)
{
$pageContent .= '
<tr>
<td>'.$itDesc.'</td>
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
<td>R'.number_format($itPrice1*$amount, 2).'</td>
</tr>
';
}
}
}
This row is producing a syntax error:
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
What is the problem here for starters?
Secondly, how would I need to do to accomplish the task that I am facing?
Any input on this would be greatly appreciated!
Could you try this?
<td>'.($item[$itId] == $amount[$itId] ? $amount : '').'</td>
This is a ternary operator, look at http://en.wikipedia.org/wiki/Ternary_operation
You can't simply add conditional statements like that while you're building a string.
You can do this, however
<td>' . ($item[$itId] == $amount[$itId]) ? $amount : null . '</td>
but you should use a more legible method.
Another issue you may get is if $amount is an array, you won't be able to print it as a string. If, however, $amount is an object with ArrayAccess interface, you can print it with the __toString() method; but that's another story.
The code for creating the cart page has several issues.
You walk over items and over quantities, which will probably give you duplicate outputs.
$item is a plain string, so I wonder what $item[$itId] is supposed to do?
You walk over your complete result set several times which actually is not necessary. I really hope that "$productSql" isn't a "select * from product", otherwhise this might get REAL slow in production mode.
I suggest creating a good SQL for getting the data and using this as a basis for filling the page:
// note this has SQL-injection issues, so you really need to make sure that $order contains no crap
$productsSql = mysql_query("select * from product where id in (".join($order, ',').")");
// you now have a result set with all products from your order.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
// session contains the quantity array mapping ID -> Quantity, so grab it from there
$itQuantity = $quantity[$itId];
// finally calculate the price
$itPrice = number_format($itPrice1*$itQuantity, 2);
// now you have all data for your template and can just insert it.
// if you use double quotes you can put the $xyz into the string directly
$pageContent .= "
<tr>
<td>$itDesc</td>
<td>$itQuanty</td>
<td>R $itPrice</td>
</tr>
";
}

Resources