Database execution with Opencart - opencart

I am using this module which allows me to run a simple blog / news feed in OC which does what I need apart from one thing, I need to display the first 4 articles on the homepage.
I have got the following so far:
<?php
$sql = "SELECT * FROM " . DB_PREFIX . "blog b LEFT JOIN " . DB_PREFIX . "blog_description bd ON (b.blog_id = bd.blog_id) WHERE b.status = 1 AND b.date <= NOW() AND bd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
$query = $this->db->query($sql);
$blogs = array();
?>
<div class="box" id="news">
<div class="title">
<p>Latest News</p>
</div>
<div class="content">
<?php
foreach($query->rows as $result){
$blogs[] = $result;
}
?>
</div>
</div>
I have been developing OC templates for a while but modules are a whole new ball game for me, any help would be appreciated

First of all You should learn and understand how the MVC (or whatever it tends to be) is implemented in OpenCart - we have controllers, models and view templates.
Your approach is mixing all the controller and model part into a view template which is completely wrong.
So what should go where:
SQL query should go into the model
A new method for retrieving the data from the model and preparing it for the view template should go into the controller
Only HTML markup should be present in the view template
Let's say the extension You have downloaded has a controller here: catalog/controller/information/news.php - You should extend it's index() (or other appropriate) method (or even create a new one if needed) so that it calls the news model where You place Your new method getLastFourArticles() which should look like:
public function getLastFourArticles() {
$sql = "
SELECT *
FROM " . DB_PREFIX . "blog b
LEFT JOIN " . DB_PREFIX . "blog_description bd ON b.blog_id = bd.blog_id
WHERE b.status = 1
AND b.date <= NOW()
AND bd.language_id = " . (int)$this->config->get('config_language_id') . "
ORDER BY b.date DESC
LIMIT 4";
return $this->db->query($sql);
}
ORDER BY part will sort the blog entries from the newest to the latest and the LIMIT 4 part will make sure we only receive 4 rows maximally.
Now in the controller You should do something like:
$this->data['latest_entries'] = $this->model_information_news->getLastFourArticles();
while expecting the model to be catalog/model/information/news.php and that it is loaded ($this->load->model('information/news');).
Now in Your template only this part is needed:
<div class="box" id="news">
<div class="title">
<p>Latest News</p>
</div>
<div class="content">
<?php foreach($latest_entries as $entry) { ?>
<span class="date"><?php echo $entry['date']; ?></span>
<span class="entry"><?php echo $entry['text']; ?></span>
<?php } ?>
</div>
</div>
Keep in mind this is only instruction-like answer and You should pass in the right names and variables (and indices for the blog entry in the template).

Related

How to display units for opencart?

Tell me how to display units for opencart 2.3. When the goods were measured in grams, I simply added the "gr" after the weight was displayed. And now I need to display "liters" as well, as now this crutch has outlived itself. How to address the variable that is responsible for the output of units (gr, kg, l) ??
This is how I used to get weight
<?php if($product['weight']>0) { ?>
<div class="weight">
<?php echo $product['weight']; ?>гр.
</div>
<?php } ?>
In the “popular” module and in the categories and in the product’s card itself, I derive the weight using the code above. But this code does not display the units (grams, kilograms, tons) that I choose in the admin panel when creating the product.
Everything that is highlighted with red colour needs to be displayed automatically from the admin panel.
Based on your example weight php code, I assume you mean how to display the weight with unit in the product page.
The code I am attaching below will help you do that easily.
Open file:
catalog/model/catalog/product.php
Find line:
public function getProduct($product_id) {
Before the line mentioned above add the following code:
public function getProductWeightWithUnit($product_id) {
$product_info = $this->getProduct($product_id);
$query = $this->db->query("SELECT unit FROM `" . DB_PREFIX . "weight_class_description` WHERE
weight_class_id='".$product_info['weight_class_id']."'");
if ($query->num_rows) {
return number_format($product_info['weight'],2) . " " . $query->row['unit'];
} else {
return false;
}
}
Save changes and close the file.
Now, open file:
catalog/controller/product/product.php
Find line:
if ($product_info['minimum']) {
Before the line mentioned above add the following code:
if ($product_info['weight']) {
$data['weight'] = $this->model_catalog_product->getProductWeightWithUnit($this->request->get['product_id']);
} else {
$data['weight'] = false;
}
Now, the backend code is ready. Based on the theme that you use, you need to edit the correct product.tpl file from your theme. For example if you use the default theme, then the file to edit is the following:
catalog/view/theme/default/template/product/product.tpl
Find the line:
<li><?php echo $text_stock; ?> <?php echo $stock; ?></li>
and add the following code after:
<li><?php echo $weight; ?></li>
The above example will show the weight like this:

Removing one item from opencart cart removes everything

My client is using an Opencart v2.1.0.2. The problem is when I remove a single item from the cart, all other items also gets removed. Yes, it's using a custom template and here's the line that calls for the delete function:
<td class="text-center"><button type="button" onclick="cart.remove('<?php echo $product['cart_id']; ?>');" title="<?php echo $button_remove; ?>" class="btn btn-danger btn-xs"><i class="fa fa-times"></i></button></td>
I also need to find out what js file is being called when this button is clicked. If it'll help, this I think this is the function from the cart.php library that opencart runs when deleting an item from the cart:
public function remove($cart_id) {
$this->db->query("DELETE FROM " . DB_PREFIX . "cart WHERE cart_id = '" . (int)$cart_id . "' AND customer_id = '" . (int)$this->customer->getId() . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "'");
}
DELETE FROM
removes everything. It's missing the product id of what it's trying to remove.
WHERE only specifies: cart_id, customer_id and session_id - so this query removes everything matching that criteria. It doesn't hone in on a specific product, so it'll take them all.
Without knowing what variable it uses for the product ID, a proper query would be something like:
public function remove($cart_id) {
$this->db->query("DELETE '".(int)$this->request->post['product_id']."' FROM " . DB_PREFIX . "cart WHERE cart_id = '" . (int)$cart_id . "' AND customer_id = '" . (int)$this->customer->getId() . "' AND session_id = '" . $this->db->escape($this->session->getId()) . "'");
}
(int)$this->request->get['product_id'] being the $_GET request for most product id calls.
Another instance could be:
(int)$this->request->post['product_id'] for a $_POST call
The template may also do something like $product_id so check what variable its using if the post/get doesn't work.
Once you got the query tightened up, the javascript button only specifies a cart id (not a product). Get your product ID in there if you want my example to work. You'll need to pass both the product_id and cart_id; else, without cart_id, if other shoppers have the same item at the same time, one person removing it would remove for them all.

DOMXPath - Select only a few items

Let's say we have this html and the following DOMXPath code:
<div>
<div>
<p>1</p>
</div>
<div>
<p>2</p>
</div>
<div>
<p>3</p>
</div>
<div>
<p>4</p>
</div>
<div>
<p>5</p>
</div>
<div>
<p>6</p>
</div>
</div>
$doc = new DOMDocument();
$doc->loadHtml($strhtml);
$doc->preserveWhiteSpace = false;
$xpath = new DOMXPath( $doc );
$nodelist = $xpath->query('//div/div[2]/p');
foreach( $nodelist as $node ) {
$result = $node->nodeValue."\n";
}
echo $result;
Obviously, $result = '2', since we asked for the value of 'p' from the second 'div' node.
Now, how can I get the values for, say, from 'div[2]' to 'div[4]' and sum them?
To be precise, I would like to know how to get "from # to #" and also how to get "this #, that #, also # and #". So two questions, for two different problems.
Thanks in advance.
You are able to select range of elements with DOMXPath:
as for the first problem to get "from # to #" use the
following approach:
// select nodes within specified range of positions
$nodelist = $xpath->query('//div/div[position()>1 and position()<5]');
as for the second problem to get "this #, that #, also # and #"
try the following (with | union operator):
// extracts the 2nd, 4th and 6th elements respectively
$nodelist = $xpath->query('//div/div[2] | //div/div[4] | //div/div[6]);

OpenCart show weight units in product page 1.5.6

How can I show the the weight (with units) in product page in 1.5.6.
Example: Weight - 2.5 kg; Weight - 250 mg ...
I've been reading some articles, but nothing working correctly.
You can format weight with Opencart's weight class format() method like this:
$this->weight->format($weight,$weight_class_id);
The getProduct() method already supplies both values you need so you can easily call it from the product controller like so:
$this->data['product_weight'] = $this->weight->format($product_info['weight'],$product_info['weight_class_id']);
Then display $product_weight wherever you want in the tpl as you would any other variable. This will give you exactly what you want but with no space (i.e., '250mg').
If you want more control over the formatting, you can also get only the unit abbreviation (e.g., 'kg', 'oz', 'lb', etc) with the getUnit() method like this:
$this->weight->getUnit($product_info['weight_class_id']);
You could then put them together however you want. If you want a space for instance:
$this->data['product_weight'] = $product_info['weight'] . ' ' . $this->weight->getUnit($product_info['weight_class_id']);
go to catalog/language/english/product/product.php,Find:
$_['text_model'] = 'Product Code:';
Add below code after it
$_['text_weight'] = 'Weight:';
open catalog/controller/product/product.php, Find:
$data['text_stock'] = $this->language->get('text_stock');
Add below code after it:
$data['text_weight'] = $this->language->get('text_weight');
In same file search for the code:
$data['model'] = $product_info['model'];
Paste below code after it:
$data['weight'] = $product_info['weight'];
$tablewunit = $this->db->query("SELECT wcd.unit FROM " . DB_PREFIX . "weight_class_description wcd WHERE (wcd.weight_class_id = " . $product_info['weight_class_id'] . ") AND wcd.language_id = '" . (int)$this->config->get('config_language_id') . "'");
$data['weight_unit'] = $tablewunit->row['unit'];
Now open catalog/view/theme/---yourtheme---/template/product/product.tpl, and find:
<li><?php echo $text_stock; ?> <?php echo $stock; ?></li>
Add below code after it:
<td><b><?php echo $text_weight; ?></b></td>
<td><?php echo round ($weight, 2) . ' ' . $weight_unit; ?></td>
<tr>
<?php if ($weight) { ?>
<tr>
<?php } ?>
Thats all
Hello fellow Bulgarian i assume by your name.
If you want to display weight on products it's very simple.
Open your FTP and go to catalog/view/theme/YOURTHEME/template/product and download product.tpl
find this line
<span class="reward"><small><?php echo $text_points; ?> <?php echo $points; ?></small></span><br />
<?php } ?>
Right after it paste this
<?php
echo round($weight,2). "kg";
?>
(Or paste it where ever you want to see it on the product page.)
after that go to /catalog/controller/product and open product.php
find this line
$this->data['model'] = $product_info['model'];
and right after it paste this line:
$this->data['weight'] = $product_info['weight'];
and you are pretty much done with that.
Hopefully i understood your question correctly.

PHP Update Query didnt works

I have one form text field in index.php and i fill 8080
http_port : <input size="5" name="http_port" value="3128">
and table 'squid' like this
no | tag | value
1 | http_port | 3128
when i click submit button its redirect to submit.php but the table didnt update the value or still 3128.
submit.php
<?php
include("conn.php");
$value = $_POST['http_port'];
$query = mysql_query("update squid set http_port='$value' where '$no'=1");
echo "Update was Succesful<br>
Bac";
?>
whats wrong with my script? Thanks and sorry for my bad english :)
There's a mistake in your mysql_query call, it should be:
$query = mysql_query("update squid set tag ='$value' where no=1");
I haven't coded anything in PHP for ages, but there are plenty of tutorials for such simple MySQL/PHP forms. Code I provided updates tag column, and in similar way you can update other columns...
$query = mysql_query("update squid set value ='$value' where no=1 and tag = 'http_port'");
Try this:
index.html:
<html>
<body>
<form action="submit.php" method="post">
http_port :
<input size="5" name="http_port" value="3128" />
<input type="submit" />
</form>
</body>
</html>
submit.php:
<?php
require("conn.php");
if(isset($_POST['http_port']))
{
$value = $_POST['http_port'];
//You should sanitize data before inserting into table
$value = mysql_real_escape_string(htmlentities(strip_tags(trim($value))));
$no="your table field name";
$sql = "UPDATE squid SET http_port=".$value." where ".$no."=1";
$query = mysql_query($sql) OR die("Err:".mysql_error());
echo "Update was Successful<br />Back";
}
else
{
echo "Something else";
}
?>
$value is in single quotes so will not get the value of variable $value.
$sql = "update squid set http_port='".$value."'where no=1";