I am working on an e-commerece website.I am using sessions as part of my cart system. On the main categories/shop page, the site should load all the items in a category unless it is already in their cart. If the cart is not even set/is empty, it automatically should load all items.
The problem is that, even when I add an item to the cart, it still displays it. I figured out, for some reason, it is not recognizing $_SESSION['cart'] as being set. This is particularly odd because the header, which makes use of a custom cart class that uses $_SESSION['cart'], works as it should (it displays the correct number of items.
What might the issue be?
shop.php
<?php
include("header.php");
$catID = $_GET['cat'];
$db = new pdoAccess("localhost","root","");
$items = $db->getItemsByCategory($catID, "stock");
$category = $db->getCategoryName($catID, "categories");
?>
<div id='mainContent'>
<div class='row'>
<h2 class="categoryHeader"> <?php echo $category;?></h2>
</div>
<?php
foreach($items as $item) {
if(!isset($_SESSSION['cart'])) {
echo "<h2>Cart Not Set!</h2><div class='col-sm-4 well'><div class='row'><img class='img-responsive' src='img/items/$item->image'></div><div class='row itemTitle'><a href='item.php?id=$item->id'>$item->name</a></div><div class='row price'>Price: $item->price</div><div class='row condition'>Condition: $item->condition</div> </div>";
} else {
if(array_search($item->id, $_SESSSION['cart']) == false) { // the item is not in the cart
echo "<h2>" . $_SESSSION['cart'] . "</h2>";
echo "<div class='col-sm-4 well'><div class='row'><img class='img-responsive' src='img/items/$item->image'></div><div class='row itemTitle'><a href='item.php?id=$item->id'>$item->name</a></div><div class='row price'>Price: $item->price</div><div class='row condition'>Condition: $item->condition</div> </div>";
}
}
}
?>
</div>
<?php
include("footer.php");
?>
addCart.php
<?php
include("header.php");
$itemID = $_GET['itemID'];
$catID = $_GET['catID'];
if(isset($_SESSION['cart'])) {
array_push($_SESSION['cart'], $itemID);
} else {
$_SESSION['cart'] = array($itemID);
}
?>
Continue Shopping?
Checkout
item.php
<?php
include("header.php");
$itemID = $_GET['id'];
$db = new pdoAccess("localhost","root","");
$item = $db->getItemDetails($itemID, "stock");
$category = $db->getCategoryName($item->category, "categories");
?>
<div id='mainContent'>
<div class='row'>
<h2 class="itemHeader"> <?php echo $item->name; ?> </h2>
</div>
<div class="row">
<div class='col-md-6'>
<img class='img-responsive' src="img/items/<?php echo $item->image;?>">
</div>
<div class='well col-md-6'><ul><li>Platform: <?php echo $category; ?> </li>
<li>Condition: <?php echo $item->condition; ?></li>
<li>Price: <?php echo $item->price; ?></li>
<//ul>
</div>
</div>
<div class="row">
<div class="col-md-8">
<p><?php echo $item->description; ?></p>
</div>
<div class="col-md-4">
<form action="addCart.php" method='get'>
<input type='hidden' name='itemID' value="<?php echo $item->id;?>" />
<input type='hidden' name='catID' value="<?php echo $category;?>" />
<input type='submit' class="addToCart" value="Add to Cart">
</form>
</div>
</div>
<?php
include("footer.php");
?>
header.php
<?php
session_start();
include("pdo.php");
$cart = new cart();
$itemCount = $cart->getItemCount();
?>
<!doctype html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="scripts/main.js" /></script>
<script src="http://code.jquery.com/jquery-1.12.3.min.js" integrity="sha256-aaODHAgvwQW1bFOGXMeX+pC4PZIPsvn2h1sArYOhgXQ=" crossorigin="anonymous"></script>
<script src="scripts/bootstrap.js" /></script>
<link href="styles/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="styles/base.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<!-- Begin Header -->
<header>
<nav class='navbar navbar-inverse'>
<div class='navbar-header'>
<button class='navbar-toggle' data-toggle='collapse' data-target='headerNav'>
<span class='glyphicon glyphicon-plus-sign' />
</button>
<a class='navbar-brand' href='index.php'><img class='img-responsive' src='logo.png' /></a>
</div>
<div class='collapse navbar-collapse' id='headerNav'>
<ul class='nav navbar-nav'>
<li class='dropdown'>
<a class='dropdown-toggle' data-toggle="dropdown" href="#">Console<span class='glyphicon glyphicon-plus'></span></a>
<ul class='dropdown-menu'>
<li>Playstation</li>
<li>Wii</li>
<li>Gamecube</li>
<li>N64</li>
<li>Other</li>
</ul>
</li>
<li class='dropdown'>
<a class='dropdown-toggle' data-toggle="dropdown" href="#">Portable<span class='glyphicon glyphicon-plus'></span></a>
<ul class='dropdown-menu'>
<li>Nintendo DS</li>
<li>GB/GBC/GBA</li>
<li>Other</li>
</ul>
</li>
<li>Videos</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>Cart (<?php if($itemCount >= 1) {echo $itemCount;} else {echo "0";} ?> )</li>
<li>Contact</li>
</ul>
</div>
</nav>
</header>
...and the cart class:
class cart {
public $items = array();
function __construct() {
$pdo = new pdoAccess("localhost","root","");
$counter = 0;
if (isset($_SESSION['cart'])) { foreach($_SESSION['cart'] as $item) {
$items[$counter] = $pdo->getItemDetails($item, "items");
$counter++;
}
}
}
public function emptyCart() {
session_unset();
session_destroy();
}
public function removeItem($itemID) {
$index = array_search($itemID, $_SESSION['cart']);
unset($_SESSION['cart'][$index]);
}
public function getItemCount() {
if(isset($_SESSION['cart'])) {
return count($_SESSION['cart']);
} else {
return 0;
}
}
public function getSubtotal() {
$total = 0;
foreach($items as $item) {
$total += $item->price;
}
return $total;
}
public function getDiscount() {
$sub = $this->getSubtotal();
if($this->getItemCount >= 2) {
$discount = $sub * .1;
} else {
$discount = 0;
}
return $discount;
}
public function getTotal() {
$sub = $this->getSubtotal;
if($this->getItemCount >= 2) {
$sub +- $this->getDiscount;
}
$total = $sub + SHIPPING;
return $total;
}
}
I would appreciate any help. Thanks in advance!
Related
Like written in the title my code works okay except for the quantity for the first product when there are multiple products, where you can remove by clicking update but cant change the quantity.
<?php
include("functions/functions.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.12/css/all.css" integrity="sha384-G0fIWCsCzJIMAVNQPfjH08cyYaUtMwjJwqiRKxxE/rx96Uroj1BtIQ6MLJuheaO9" crossorigin="anonymous">
<link type="text/css" rel="stylesheet" href="styles/style.css" />
<title>Prodavnica+</title>
</head>
<body>
<div id="header" class="cf">
<img src="images/logo.png" />
<div id="navbar">
<ul>
<li>
Home
</li>
<li>
Products
</li>
<li>
My Account
</li>
<li>
Sign Up
</li>
<li>
Shopping Card
</li>
<li>
Contact Us
</li>
</ul>
</div> <!-- END navbar -->
<div id="search">
<form method="get" action="results.php" enctype="multipart/form-data">
<input type="text" name="search_query" placeholder="Search Product" />
<input type="submit" name="search_button" value="Search" />
</form>
</div>
</div> <!-- END header -->
<?php cart(); ?>
<div id="shop-bar">
<p>
Total items: <?php totalItems() ?>
</p>
<p>
Total price: <?php totalPrice()?>
</p>
<i class="fas fa-shopping-cart"> | </i>
<span> Welcome Guest! </span>
</div> <!-- END shop-bar -->
<div id="container">
<div id="main">
<div id="product-box-cart">
<form action="" method="post" enctype="multipart/form-data">
<table>
<thead>
<th>Product</th>
<th>Quantity</th>
<th>Remove</th>
<th>Price</th>
</thead>
<tbody>
<?php
$total = 0;
global $con;
$ip = getIp();
$run_price = mysqli_query($con,"SELECT * FROM cart WHERE ip_add = '$ip'");
while($row_pro_price = mysqli_fetch_array($run_price)) {
$pro_id = $row_pro_price['p_id'];
$pro_qty = $row_pro_price['qty'];
$run_pro_price2 = mysqli_query($con,"SELECT * FROM products WHERE product_id = '$pro_id'") or die(mysqli_error($con));
while($row_pro_price2 = mysqli_fetch_array($run_pro_price2)) {
$pro_price = array($row_pro_price2['product_price']);
$pro_title = $row_pro_price2['product_title'];
$product_image = $row_pro_price2['product_image'];
$single_price = $row_pro_price2['product_price'];
$pro_price_values = array_sum($pro_price);
$total += $pro_price_values;
?>
<tr>
<td>
<h2><?php echo $pro_title ?></h2>
<img src="admin/product_images/<?php echo $product_image;?>">
</td>
<td>
<input type="text" name="qty[]" value = "<?php echo $pro_qty;?>">
</td>
<td>
<input type="checkbox" name="remove[]" value="<?php echo $pro_id ?>" />
</td>
<td>
<?php echo "$" . $single_price; ?>
</td>
</tr>
</tbody>
<?php }} ?>
</table>
<p>
<b> Total Value: </b> <?php echo "$" . $total;?>
</p>
<div id="check-buttons">
<input type="submit" name="update_cart" value="Update Cart" />
<input type="submit" name="continue" value="Continue Shopping" />
<input type="button" value="Checkout" />
</div>
</form>
<?php
//pressing update cart ->
if(isset($_POST['update_cart'])) {
//removing the products
if(isset($_POST['remove'])) {
foreach($_POST['remove'] as $remove_id) {
$delete_product = "DELETE FROM cart WHERE p_id = '$remove_id' AND ip_add = '$ip'";
$run_delete = mysqli_query($con,$delete_product);
if($run_delete) {
echo "<script>window.open('cart.php','_self')</script>";
}
}
}
//quantity of product
if(isset($_POST['qty'])) {
foreach($_POST['qty'] as $qty_id) {
$update_qty = "UPDATE cart SET qty = '$qty_id' WHERE p_id = '$pro_id' AND ip_add = '$ip'";
$run_qty = mysqli_query($con, $update_qty) or die(mysqli_error($con));
}
}
}
elseif(isset($_POST['continue'])) {
echo "<script>window.open('index.php','_self')</script>";
}
?>
</div> <!-- END product box -->
</div> <!-- END main -->
<div id="side">
<div id="side-category">
<h2>Categories</h2>
<hr />
<table id="mw">
<tr>
<?php
getBrands();
?>
</tr>
</table>
<ul>
<?php
getCats();
?>
</ul>
</div><!-- END side-category-->
</div> <!-- END side -->
</div> <!--END container -->
<div id="footer">
<p>© 2018 by </p>
</div> <!-- END footer -->
</body>
</html>
This is my cart.php page where the code executes. The $pro_id variable is from GET method for adding to cart. Therefore the $pro_id = $_GET[add_cart] which is in index.php. I will also include the index.php file bellow so if needed, one can take a look.
Quick answer would mean a lot. Thanks
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.12/css/all.css" integrity="sha384-G0fIWCsCzJIMAVNQPfjH08cyYaUtMwjJwqiRKxxE/rx96Uroj1BtIQ6MLJuheaO9" crossorigin="anonymous">
<link type="text/css" rel="stylesheet" href="styles/style.css" />
<title>Prodavnica+</title>
</head>
<body>
<div id="header" class="cf">
<img src="images/logo.png" />
<div id="navbar">
<ul>
<li>
Home
</li>
<li>
Products
</li>
<li>
My Account
</li>
<li>
Sign Up
</li>
<li>
Shopping Card
</li>
<li>
Contact Us
</li>
</ul>
</div> <!-- END navbar -->
<div id="search">
<form method="get" action="results.php" enctype="multipart/form-data">
<input type="text" name="search_query" placeholder="Search Product" />
<input type="submit" name="search_button" value="Search" />
</form>
</div>
</div> <!-- END header -->
<?php cart(); ?>
<div id="shop-bar">
<p>
Total items: <?php totalItems() ?>
</p>
<p>
Total price: <?php totalPrice()?>
</p>
<i class="fas fa-shopping-cart"> | </i>
<span> Welcome Guest! </span>
</div> <!-- END shop-bar -->
<div id="container">
<div id="main">
<div id="product-box">
<?php
if(isset($_GET['cat'])) {
getCatPro();
}
elseif(isset($_GET['brand'])) {
getBrandPro();
}
else {
getPro();
}
?>
</div> <!-- END product box -->
</div> <!-- END main -->
<div id="side">
<div id="side-category">
<h2>Categories</h2>
<hr />
<table id="mw">
<tr>
<?php
getBrands();
?>
</tr>
</table>
<ul>
<?php
getCats();
?>
</ul>
</div><!-- END side-category-->
</div> <!-- END side -->
</div> <!--END container -->
<div id="footer">
<p>© 2018 by Djordje Stamenkovic</p>
</div> <!-- END footer -->
</body>
</html>
functions.php
<?php
//database connection
$con = mysqli_connect("localhost","root","","eprodavnica");
// function for getting ip address of the client
/*In this PHP function, first attempt is to get the direct IP address of client’s machine, if not available then try for forwarded for IP address using HTTP_X_FORWARDED_FOR. And if this is also not available, then finally get the IP address using REMOTE_ADDR.*/
function getIp()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
//adding a single product to cart
function cart() {
if(isset($_GET['add_cart'])) {
global $con;
$ip = getIp();
$pro_id = $_GET['add_cart'];
$run_check = mysqli_query($con,"SELECT * FROM cart WHERE ip_add = '$ip' AND p_id = '$pro_id'") or die(mysqli_error($con));
if(mysqli_num_rows($run_check)>0) {
echo "";
} else {
$run_pro = mysqli_query($con, "INSERT INTO cart (p_id, ip_add, qty) values ('$pro_id','$ip',1)") or die(mysqli_error($con));
echo "<script>window.open('index.php','_self')</script>";
}
}
}
//getting the total added items
function totalItems() {
if(isset($_GET['add_cart'])) {
global $con;
$ip = getIp();
$run_items = mysqli_query($con, "SELECT * FROM cart WHERE ip_add='$ip'");
$count_items = mysqli_num_rows($run_items);
} else {
global $con;
$ip = getIp();
$run_items = mysqli_query($con, "SELECT * FROM cart WHERE ip_add='$ip'") or die(mysqli_error($con));
$count_items = mysqli_num_rows($run_items);
}
echo $count_items;
}
//getting the total Price of items in the cart
function totalPrice() {
$total = 0;
global $con;
$ip = getIp();
$run_price = mysqli_query($con,"SELECT * FROM cart WHERE ip_add = '$ip'");
while($row_pro_price = mysqli_fetch_array($run_price)) {
$pro_id = $row_pro_price['p_id'];
$run_pro_price2 = mysqli_query($con,"SELECT * FROM products WHERE product_id = '$pro_id'");
while($row_pro_price2 = mysqli_fetch_array($run_pro_price2)) {
$pro_price = array($row_pro_price2['product_price']);
$pro_price_values = array_sum($pro_price);
$total += $pro_price_values;
}
}
echo "$" . $total;
}
//getting the categories
function getCats() {
global $con;
$run_cats = mysqli_query($con,"SELECT * FROM categories");
while($row_cats = mysqli_fetch_array($run_cats)) {
$cat_id = $row_cats['cat_id'];
$cat_title = $row_cats['cat_title'];
echo "<li>
<a href='index.php?cat=$cat_id'>$cat_title</a>
</li>";
}
}
//getting the brands
function getBrands() {
global $con;
$run_brands = mysqli_query($con,"SELECT * FROM brands");
while($row_brands = mysqli_fetch_array($run_brands)) {
$brand_id = $row_brands['brand_id'];
$brand_title = $row_brands['brand_title'];
echo "<td>
<a href='index.php?brand=$brand_id'>$brand_title</a>
</td>";
}
}
//getting products on main page
function getPro() {
if(!isset($_GET['cat'])){
if(!isset($_GET['brands'])) {
global $con;
$run_pro = mysqli_query($con,"SELECT * FROM products ORDER BY RAND() LIMIT 0,9");
while($row_pro = mysqli_fetch_array($run_pro)) {
$pro_id = $row_pro['product_id'];
$pro_cat = $row_pro['product_cat'];
$pro_brand = $row_pro['product_brand'];
$pro_title = $row_pro['product_title'];
$pro_price = $row_pro['product_price'];
$pro_image = $row_pro['product_image'];
echo "
<div class='single-product cf'>
<h4><a href='#'>$pro_title</a></h4>
<a href='details.php?pro_id=$pro_id'><img src='admin/product_images/$pro_image' /></a>
<p>
Price: $ $pro_price
</p>
<a href='index.php?add_cart=$pro_id'><button>Add To Cart</button></a>
</div>
";
}
}
}
}
//getting the category products
function getCatPro() {
if(isset($_GET['cat'])){
$cat_id = $_GET['cat'];
global $con;
$run_cat_pro = mysqli_query($con,"SELECT * FROM products WHERE product_cat = '$cat_id'");
$count_cats = mysqli_num_rows($run_cat_pro);
if($count_cats == 0) {
echo "<div class='no-cat'>
<h1> We're sorry! There are currently no products with that category. :(</h1>
</div>";
} else {
while($row_cat_pro = mysqli_fetch_array($run_cat_pro)) {
$pro_id = $row_cat_pro['product_id'];
$pro_cat = $row_cat_pro['product_cat'];
$pro_brand = $row_cat_pro['product_brand'];
$pro_title = $row_cat_pro['product_title'];
$pro_price = $row_cat_pro['product_price'];
$pro_image = $row_cat_pro['product_image'];
echo "
<div class='single-product cf'>
<h4><a href='#'>$pro_title</a></h4>
<a href='details.php?pro_id=$pro_id'><img src='admin/product_images/$pro_image' /></a>
<p>
Price: $ $pro_price
</p>
<a href='index.php?add_cart=$pro_id'><button>Add To Cart</button></a>
</div>
";
}
}
}
}
//getting the brand products (in this case sex)
function getBrandPro() {
if(isset($_GET['brand'])){
$brand_id = $_GET['brand'];
global $con;
$run_brand_pro = mysqli_query($con,"SELECT * FROM products WHERE product_brand = '$brand_id'") or die(mysqli_error($con));
$count_brands = mysqli_num_rows($run_brand_pro);
if($count_brands == 0) {
echo "<div class='no-cat'>
<h1> We're sorry! There are currently no products for that sex. :(</h1>
</div>";
} else {
while($row_brand_pro = mysqli_fetch_array($run_brand_pro)) {
$pro_id = $row_brand_pro['product_id'];
$pro_cat = $row_brand_pro['product_cat'];
$pro_brand = $row_brand_pro['product_brand'];
$pro_title = $row_brand_pro['product_title'];
$pro_price = $row_brand_pro['product_price'];
$pro_image = $row_brand_pro['product_image'];
echo "
<div class='single-product cf'>
<h4><a href='#'>$pro_title</a></h4>
<a href='details.php?pro_id=$pro_id'><img src='admin/product_images/$pro_image' /></a>
<p>
Price: $ $pro_price
</p>
<a href='index.php?add_cart=$pro_id'><button>Add To Cart</button></a>
</div>
";
}
}
}
}
NOTE: It works fine when one product is in the cart.
I have a block being displayed on my homepage which shows a product, whose id we specify. The code on homepage (static block) looks like this:
{{block type="core/template" product_id="2559" template="catalog/product/one_product.phtml"}}
The one_product.phtml file contains this code:
<?php
$productId = $this->getProduct_id();
$product = Mage::getModel('catalog/product')->load($productId); //load product
?>
<div class="product">
<a href="<?php echo $product->getProductUrl() ?>" >
<img class="product-img" src="<?php echo $this->helper('catalog/image')->init($product, 'image'); ?>"alt="<?php echo $this->htmlEscape($product->getName()) ?>" />
</a>
</div>
<div class="product-detail">
<P><?php // echo $this->htmlEscape($product->getName()) ?>
<?php $prod_name = $this->htmlEscape($product->getName()); ?>
<?php
$count_str = strlen($prod_name);
if ($count_str < 40) {
echo $prod_name;
} else {
$offset = 0;
$length = 41;
$prod_name = html_entity_decode($prod_name);
echo htmlentities(mb_substr($prod_name,0,$length,'utf-8')). "...";;
}
?>
</P>
<!--?php $price = $product->getPrice() ; ?-->
<?php $_product = Mage::getModel('catalog/product')->load($product->getId());
$productBlock = $this->getLayout()->createBlock('catalog/product_price');
?>
<span>
<?php echo $productBlock->getPriceHtml($_product); ?>
<?php $tier_price = end($_product->getTierPrice());
if($tier_price !='0'){ ?>
<span>As Low As:</span>
<?php
echo " ₹ ".number_format( $tier_price['price']);
} ?>
<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart"
onclick="setLocation('<?php echo Mage::helper('checkout/cart')->getAddUrl($product); ?>')">
</span>
</div>
So basically I want to show random products out of the ones I specify separated by commas. For eg: I specify in the static block product_id="2559,2661,2857,9293" and it should show any one of those 4 products randomly.
What is the way to do that?
Also any way to make it pull products from SKU also? Since we remember all the SKUs but we have to check each product ID everytime we change the product here.
Please excuse me if the question is too basic, I'm not a developer.
You can see it in action at www.giftzila.com
Thanks!
Create a new file called random-product.phtml at app/design/frontend/default/Your_Theme/template/catalog/random-product.phtml then add the following code in that file
<?php
$chosen_category = Mage::getModel('catalog/category')->load($this->getCategoryId());
$_productCollection = $this->getLoadedProductCollection();
$number_of_products = $this->getNumProducts();
if (sizeof($_productCollection) < $number_of_products) {
$number_of_products = sizeof($_productCollection);
}
$displayed_products = array();
foreach ($_productCollection as $_product) {
$displayed_products[] = $_product;
}
$random_products = array();
if (sizeof($_productCollection) > 1) {
$random_products = array_rand($displayed_products, $number_of_products);
} else {
$random_products = array('0');
}
?>
<?php if(!$_productCollection->getSize()):?>
<div class="note-msg">
<?=$this->__('There are no products matching the selection.')?>
</div>
<?php else:?>
<div class="main-binder">
<div class="cms-box">
<div class="category-title">
<h2>Random Products</h2>
</div>
<div class="category-products">
<table id="products-grid-table" class="products-grid">
<?php
$k=0;
for ($i=0; $i < $number_of_products; $i++): ?>
<?php if ($k == 0) { ?>
<tr class="first odd">
<?php } if($k==3) { $k=0; ?>
</tr><tr class="first odd even">
<?php } ?>
<td id="td_<?php echo ($k+1); ?>" <?php if($k==3){ ?>class="last"<? } ?> >
<div class="cms-box">
<div id="cont_<?php echo ($k+1); ?>">
<div class="product-name-block">
<?php
$pname=$this->htmlEscape($displayed_products[$random_products[$i]]->getName());
?>
<h3 class="product-name">
<a href="<?php echo $displayed_products[$random_products[$i]]->getProductUrl()?>" title="<?php echo $pname; ?>">
<?php if(strlen($pname) > 28) {echo substr($pname,0,25)."...";}else {echo $pname;}?>
</a></h3>
</div>
<div class="image-box">
<a class="product-image" href="<?php echo $displayed_products[$random_products[$i]]->getProductUrl()?>"> <img src="<?php echo $this->helper('catalog/image')->init($displayed_products[$random_products[$i]], 'small_image')->resize(140);?>" alt="<?php echo $this->htmlEscape($displayed_products[$random_products[$i]]->getName())?>" title="<?php echo $this->htmlEscape($displayed_products[$random_products[$i]]->getName())?>"/> </a>
</div>
<div class="cms-price-box" style=" text-align:center;">
<span class="regular-price" id="product-price-37">
<span class="price" ><?php echo Mage::app()->getLocale()->currency(Mage::app()->getStore()->
getCurrentCurrencyCode())->getSymbol().$displayed_products[$random_products[$i]]->getPrice(); ?></span>
</span>
</div>
<div class="button-row" style="text-align:center;">
<button onclick="setLocation('<?php echo $displayed_products[$random_products[$i]]->getProductUrl();?>')" class="button" type="button"><span><span><span>Details</span></span></span></button>
<button onclick="setLocation('<?php echo $this->getUrl('')."/checkout/cart/add?product=".$displayed_products[$random_products[$i]]->getId()."&qty=1" ?>')" class="button"><span><?php echo $this->__('Add to Cart') ?></span></button>
</div>
</div>
</div></td>
<?php $k++; ?>
<?php endfor;?>
</tr>
</table>
</div>
</div>
</div>
<?php endif;?>
Now call block in your cms home page by adding following code:-
{{block type="catalog/product_list" category_id="3" num_products="8" template="catalog/random-product.phtml"}}
I am trying to get a bootstrap carousel to perform like this example below but with some php code.
http://www.bootply.com/81478
But with php code where it has row and columns. I have 5 images that I have displayed but each one for some reason comes in as a new slide.
It should show about 4 - 5 images on one row. But with my php code does not seem to work properly only shows one image each slide.
My Question is: In my view is there any way to be able to make each slide to display about 4 images.
My View Is
<div id="carousel-thumbnail<?php echo $module;?>" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<?php foreach ($banners as $i => $banner) { ?>
<li data-target="#carousel-thumbnail<?php echo $module; ?>" data-slide-to="<?php echo $i; ?>"<?php echo !$i ? ' class="active"' : ''; ?>></li>
<?php } ?>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<?php foreach ($banners as $i => $banner) { ?>
<div class="item<?php echo !$i ? ' active' : ''; ?>">
<div class="row">
<div class="col-lg-3">
<img src="<?php echo $banner['src']; ?>" class="img-thumbnail">
</div>
</div>
</div>
<?php } ?>
</div>
<!-- Controls -->
<?php if (count($banners) > 1) { ?>
<a class="carousel-control left" href="#carousel-thumbnail<?php echo $module; ?>" data-slide="prev">‹</a>
<a class="carousel-control right" href="#carousel-thumbnail<?php echo $module; ?>" data-slide="next">›</a>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#carousel<?php echo $module;?>').carousel({
interval: 10000
});
});
</script>
My Controller
<?php
class Carousel extends MX_Controller {
public function __construct() {
parent::__construct();
}
public function index($info) {
static $module = 0;
$data['banners'] = array();
$banners = $this->get_banner($info[0]['module_display_id']);
foreach ($banners as $banner) {
if (is_file(FCPATH . 'images/' . $banner['banner_image'])) {
$data['banners'][] = array(
'src' => base_url() . 'images/' . $banner['banner_image']
);
} else {
$data['banners'][] = array(
'src' => $banner['banner_image']
);
}
}
$data['module'] = $module++;
$this->load->view('theme/default/template/module/carousel', $data);
}
public function get_banner($banner_id) {
$this->db->select('*');
$this->db->from('banner b', 'LEFT');
$this->db->join('banner_image bi', 'bi.banner_id = b.banner_id', 'LEFT');
$this->db->where('b.banner_id', $banner_id);
$this->db->where('b.banner_status', '1');
$this->db->order_by('banner_sort_order', 'ASC');
$query = $this->db->get();
return $query->result_array();
}
}
PHP code for groups of four images
Indicators
Each item is a group of four images. The indicator indicates the group, rather than the image. Therefore, the number of indicators is four times less than the number of images.
<!-- Indicators -->
<ol class="carousel-indicators">
<?php for ($i = 0; $i < ceil(count($banners) / 4); $i++) { ?>
<li data-target="#carousel-thumbnail<?php echo $module; ?>" data-slide-to="<?php echo $i; ?>"<?php echo !$i ? ' class="active"' : ''; ?>></li>
<?php } ?>
</ol>
Items
You need to wrap in the row a series of four slide, rather than one by one:
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<div class="row">
<?php foreach ($banners as $i => $banner) { ?>
<?php if (($i > 0) && ($i % 4 == 0)) { ?>
</div>
</div>
<div class="item">
<div class="row">
<?php } ?>
<div class="col-lg-3">
<img src="<?php echo $banner['src']; ?>" class="img-thumbnail">
</div>
<?php } ?>
</div>
</div>
</div>
first off, I'm extremely new to PHP.
I'm using Conrete5, and I have a new template to an image slider. This is what I'm using:
http://codepen.io/altitudems/pen/KdgGLG
There's a placeholder image, which I'm trying to replace by grabbing the first image set in the block itself. Here is my view file from the actual block:
<?php defined('C5_EXECUTE') or die("Access Denied.");
$navigationTypeText = ($navigationType == 0) ? 'arrows' : 'pages';
$c = Page::getCurrentPage();
if ($c->isEditMode()) { ?>
<div class="ccm-edit-mode-disabled-item" style="width: <?php echo $width; ?>; height: <?php echo $height; ?>">
<div style="padding: 40px 0px 40px 0px"><?php echo t('Image Slider disabled in edit mode.')?></div>
</div>
<?php } else { ?>
<script>
$(document).ready(function(){
$(function () {
$("#ccm-image-slider-<?php echo $bID ?>").responsiveSlides({
prevText: "", // String: Text for the "previous" button
nextText: "",
<?php if($navigationType == 0) { ?>
nav:true
<?php } else { ?>
pager: true
<?php } ?>
});
});
});
</script>
<div class="ccm-image-slider-container ccm-block-image-slider-<?php echo $navigationTypeText?>" >
<div class="ccm-image-slider">
<div class="ccm-image-slider-inner">
<?php if(count($rows) > 0) { ?>
<ul class="rslides" id="ccm-image-slider-<?php echo $bID ?>">
<?php foreach($rows as $row) { ?>
<li>
<?php if($row['linkURL']) { ?>
<?php } ?>
<?php
$f = File::getByID($row['fID'])
?>
<?php if(is_object($f)) {
$tag = Core::make('html/image', array($f, false))->getTag();
if($row['title']) {
$tag->alt($row['title']);
}else{
$tag->alt("slide");
}
print $tag; ?>
<?php } ?>
<div class="ccm-image-slider-text">
<?php if($row['title']) { ?>
<h1 class="ccm-image-slider-title"><?php echo $row['title'] ?></h1>
<?php } ?>
<?php echo $row['description'] ?>
</div>
</li>
<?php } ?>
</ul>
<?php } else { ?>
<div class="ccm-image-slider-placeholder">
<p><?php echo t('No Slides Entered.'); ?></p>
</div>
<?php } ?>
</div>
</div>
</div>
<?php } ?>
Here is my gallery view file:
<a class="gallery-launcher" href="#gallery1"> // Location of the image
<div class="overlay">
<div class="overlay-content">
<button class="btn btn-default">Open Gallery</button>
</div>
</div>
</a>
<div class="gallery inactive" id="gallery1">
<div class="gallery-item">
//Fullscreen gallery code here
</div>
</div>
Where it says // Location of the image is where I need to have the first image set. I can't figure out what I'd put there? Any help will be appreciated.
You could use the concrete5 file helper to get the file path, like this for example:
$f = File::getByID($row['fID']);
$relpath = $f->getRelativePath();
In general I suggest that you read more about the concrete5 file functions to understand more how it works:
I have created some custom code (lines 287-309 in the code below)It is a duplicate function of 313-345 but with a few changes.
Although the function works perfectly well for some reason the page upon change or refresh duplicate the collection at the bottom of the page.
If I move lines 287-309 to line 347 onwards this does not happen. I'm assuming I a creating some sort of loop here or am I not closing the PHP correctly?
Any help would be hugely appreciated.
The Code:
<?php
include "../include/db.php";
include "../include/authenticate.php";
include "../include/general.php";
include "../include/resource_functions.php";
include "../include/collections_functions.php";
hook("homeheader");
include "../include/header.php";
if (!hook("replacehome")) {
if (!hook("replaceslideshow")) {
# Count the files in the configured $homeanim_folder.
$dir = dirname(__FILE__) . "/../" . $homeanim_folder;
$filecount = 0;
$checksum=0; # Work out a checksum which is the total of all the image files in bytes - used in image URLs to force a refresh if any of the images change.
$d = scandir($dir);
sort($d, SORT_NUMERIC);
$reslinks=array();
foreach ($d as $f) {
if(preg_match("/[0-9]+\.(jpg)/",$f))
{
$filecount++;
$checksum+=filesize($dir . "/" . $f);
$linkfile=substr($f,0,(strlen($f)-4)) . ".txt";
$reslinks[$filecount]="";
if(file_exists("../" . $homeanim_folder . "/" . $linkfile))
{
$linkref=file_get_contents("../" . $homeanim_folder . "/" . $linkfile);
$linkaccess = get_resource_access($linkref);
if (($linkaccess!=="") && (($linkaccess==0) || ($linkaccess==1))){$reslinks[$filecount]=$baseurl . "/pages/view.php?ref=" . $linkref;}
}
}
}
$homeimages=$filecount;
if ($filecount>1) { # Only add Javascript if more than one image.
?>
<script type="text/javascript">
var num_photos=<?php echo $homeimages?>; // <---- number of photos (/images/slideshow?.jpg)
var photo_delay=5; // <---- photo delay in seconds
var link = new Array();
<?php
$l=1;
foreach ($reslinks as $reslink)
{
echo "link[" . $l . "]=\"" . $reslink . "\";";
$l++;
}
?>
var cur_photo=2;
var last_photo=1;
var next_photo=2;
flip=1;
var image1=0;
var image2=0;
function nextPhoto()
{
if (!document.getElementById('image1')) {return false;} /* Photo slideshow no longer available (AJAX page move) */
if (cur_photo==num_photos) {next_photo=1;} else {next_photo=cur_photo+1;}
image1 = document.getElementById("image1");
image2 = document.getElementById("photoholder");
sslink = document.getElementById("slideshowlink");
linktarget=link[cur_photo];
if (flip==0)
{
// image1.style.visibility='hidden';
//Effect.Fade(image1);
jQuery('#image1').fadeOut(1000)
window.setTimeout("image1.src='<?php echo $baseurl . "/" . $homeanim_folder?>/" + next_photo + ".jpg?checksum=<?php echo $checksum ?>';if(linktarget!=''){jQuery('#slideshowlink').attr('href',linktarget);}else{jQuery('#slideshowlink').removeAttr('href');}",1000);
flip=1;
}
else
{
// image1.style.visibility='visible';
//Effect.Appear(image1);
jQuery('#image1').fadeIn(1000)
window.setTimeout("image2.style.background='url(<?php echo $baseurl . "/" . $homeanim_folder?>/" + next_photo + ".jpg?checksum=<?php echo $checksum ?>)';if(linktarget!=''){jQuery('#slideshowlink').attr('href',linktarget);}else{jQuery('#slideshowlink').removeAttr('href');}",1000);
flip=0;
}
last_photo=cur_photo;
cur_photo=next_photo;
timers.push(window.setTimeout("nextPhoto()", 1000 * photo_delay));
}
jQuery(document).ready( function ()
{
/* Clear all old timers */
ClearTimers();
timers.push(window.setTimeout("nextPhoto()", 1000 * photo_delay));
}
);
</script>
<?php } ?>
<div class="HomePicturePanel"
<?php if (isset($home_slideshow_width)) {
echo "style=\"";
$slide_width = $home_slideshow_width + 0;
echo"width:" . (string)$slide_width ."px; ";
echo "\" ";
}
?>>
<a id="slideshowlink"
<?php
$linkurl="#";
if(file_exists("../" . $homeanim_folder . "/1.txt"))
{
$linkres=file_get_contents("../" . $homeanim_folder . "/1.txt");
$linkaccess = get_resource_access($linkres);
if (($linkaccess!=="") && (($linkaccess==0) || ($linkaccess==1))) {$linkurl=$baseurl . "/pages/view.php?ref=" . $linkres;}
echo "href=\"" . $linkurl ."\" ";
}
?>
\>
<div class="HomePicturePanelIN" id='photoholder' style="
<?php
if (isset($home_slideshow_height)){
echo"height:" . (string)$home_slideshow_height ."px; ";
}
?>
background-image:url('<?php echo $baseurl . "/" . $homeanim_folder?>/1.jpg?checksum=<?php echo $checksum ?>');">
<img src='<?php echo $baseurl . "/" . $homeanim_folder?>/2.jpg?checksum=<?php echo $checksum ?>' alt='' id='image1' style="display:none;<?php
if (isset($home_slideshow_width)){
echo"width:" . $home_slideshow_width ."px; ";
}
if (isset($home_slideshow_height)){
echo"height:" . $home_slideshow_height ."px; ";
}
?>">
</div>
</a>
<div class="PanelShadow"></div>
</div>
<?php } # End of hook replaceslideshow
?>
<?php if (checkperm("s")) {
hook("homebeforepanels");
?>
<?php if ($home_themeheaders && $enable_themes) { ?>
<div class="HomePanel"><div class="HomePanelIN">
<h2><a onClick="return CentralSpaceLoad(this,true);" href="<?php echo $baseurl_short?>pages/themes.php"><?php echo $lang["themes"]?></a></h2>
<?php echo text("themes")?>
<br /> <br />
<select style="width:140px;" onChange="CentralSpaceLoad(this.value,true);">
<option value=""><?php echo $lang["select"] ?></option>
<?php
$headers=get_theme_headers();
for ($n=0;$n<count($headers);$n++)
{
?>
<option value="<?php echo $baseurl_short?>pages/themes.php?header=<?php echo urlencode($headers[$n])?>"><?php echo i18n_get_translated(str_replace("*","",$headers[$n]))?></option>
<?php
}
?>
</select>
<br />> <?php echo $lang["viewall"] ?>
</div>
<div class="PanelShadow"></div>
</div>
<?php } ?>
<?php if ($home_themes && $enable_themes) { ?>
<div class="HomePanel"><div class="HomePanelINtopA">
<div class="HomePanelINtopHeader"><?php echo $lang["themes"]?></div>
<div class="HomePanelINtopText"><?php echo text("themes")?></div>
</div>
<div class="PanelShadow"></div>
</div>
<?php } ?>
<?php if ($home_mycollections && !checkperm("b") && $userrequestmode!=2 && $userrequestmode!=3) { ?>
<div class="HomePanel"><div class="HomePanelINtopB">
<div class="HomePanelINtopHeader"> <?php echo $lang["mycollections"]?></div>
<div class="HomePanelINtopText"><?php echo text("mycollections")?></div>
</div>
<div class="PanelShadow">
</div>
</div>
<?php } ?>
<?php if ($home_advancedsearch) { ?>
<div class="HomePanel"><div class="HomePanelINtopC">
<div class="HomePanelINtopHeader"> <?php echo $lang["advancedsearch"]?></div>
<div class="HomePanelINtopText"><?php echo text("advancedsearch")?></div>
</div>
<div class="PanelShadow"></div>
</div>
<?php } ?>
<?php if ($home_mycontributions && (checkperm("d") || (checkperm("c") && checkperm("e0")))) { ?>
<div class="HomePanel"><div class="HomePanelINtopD">
<div class="HomePanelINtopHeader"><?php echo $lang["mycontributions"]?></div>
<div class="HomePanelINtopText"><?php echo text("mycontributions")?></div>
</div>
<div class="PanelShadow"></div>
</div>
<?php } ?>
<?php if ($home_helpadvice) { ?>
<div class="HomePanel"><div class="HomePanelINtopE">
<div class="HomePanelINtopHeader"><?php echo $lang["helpandadvice"]?></div>
<div class="HomePanelINtopText"><?php echo text("help")?></div>
</div>
<div class="PanelShadow"></div>
</div>
<?php } ?>
<?php if ($home_themes && $enable_themes) { ?>
<div class="HomePanel"><div class="HomePanelINtopIntro">
<div class="HomePanelINtopHeader"><?php echo text("welcometitle")?></div>
<div class="HomePanelINtopText"><?php echo text("welcometext")?></div>
</div>
<div class="PanelShadow"></div>
</div>
<?php } ?>
<?php
/* ------------ Customisable home page panels ------------------- */
if (isset($custom_home_panels))
{
for ($n=0;$n<count($custom_home_panels);$n++)
{
if (!hook("panelperm")) {
?>
<div class="HomePanel"><div class="HomePanelIN" <?php if ($custom_home_panels[$n]["text"]=="") {?>style="min-height:0;"<?php } ?>>
<h2><a href="<?php echo $custom_home_panels[$n]["link"] ?>" <?php if (isset($custom_home_panels[$n]["additional"])){ echo $custom_home_panels[$n]["additional"];} ?>> <?php echo i18n_get_translated($custom_home_panels[$n]["title"]) ?></a></h2>
<?php echo i18n_get_translated($custom_home_panels[$n]["text"]) ?>
</div>
<div class="PanelShadow"></div>
</div>
<?php
} // end hook 'panelperm'
}
}
?>
<!-- THIS IS LINE 287 please refer to question -->
<?php
if(!hook("EditorsPick")):
/* ------------ Collections promoted to the home page ------------------- */
$home_collectionsx=get_home_page_promoted_collectionsx(16);
foreach ($home_collectionsx as $home_collectionx)
{
?>
<div class="EditorsPick">
<div class="HomePanel"><div class="HomePanelINtopEditors">
<div class="HomePanelINtopHeader">Editors Pick</div>
<div class="HomePanelINtopText">This is the editors pick of Asset Space...</div>
<div class="EditorsPicImage"><div style="padding-top:<?php echo floor((155-$home_collectionx["thumb_height"])/2) ?>px; margin-top: -24px; margin-bottom: -15px;">
<a href="<?php echo $baseurl_short?>pages/search.php?search=!collection<?php echo $home_collectionx["ref"] ?>" onClick="return CentralSpaceLoad(this,true);"><img class="ImageBorder" src="<?php echo get_resource_path($home_collectionx["home_page_image"],false,"thm",false) ?>" width="<?php echo $home_collectionx["thumb_width"] ?>" height=" <?php echo $home_collectionx["thumb_height"] ?>" /></div>
</div></div>
</div>
</div>
</div>
<?php
}
endif; # end hook homefeaturedcol
?>
<!-- THIS IS LINE 309 please refer to question -->
<!-- THIS IS LINE 313 please refer to question -->
<?php
if(!hook("homefeaturedcol")):
/* ------------ Collections promoted to the home page ------------------- */
$home_collections=get_home_page_promoted_collections(16);
foreach ($home_collections as $home_collection)
{
?>
<div class="ResourceOfTheDay"></div>
<div class="HomePanel HomePanelPromoted"><div class="HomePanelIN HomePanelPromotedIN">
<div class="MyCollectionsHighlite"></div>
<div class="HomePanelPromotedImageWrap">
<div style="padding-top:<?php echo floor((155-$home_collection["thumb_height"])/2) ?>px; margin-top: -24px; margin-bottom: -15px;">
<a href="<?php echo $baseurl_short?>pages/search.php?search=!collection<?php echo $home_collection["ref"] ?>" onClick="return CentralSpaceLoad(this,true);"><img class="ImageBorder" src="<?php echo get_resource_path($home_collection["home_page_image"],false,"thm",false) ?>" width="<?php echo $home_collection["thumb_width"] ?>" height="<?php echo $home_collection["thumb_height"] ?>" /></div>
</div>
<p style="font-size:14px; font-weight:bold"><?php echo i18n_get_translated($home_collection["home_page_text"]) ?></p>
<p style="font-size:12px; font-weight:normal">Click to view this collection</p>
</div>
<div class="PanelShadow"></div>
</div>
<?php
}
endif; # end hook homefeaturedcol
?>
<!-- THIS IS LINE 345 please refer to question -->
<!-- THIS IS LINE 347 please refer to question -->
<div class="clearerleft"></div>
<?php }
} // End of ReplaceHome hook
include "../include/footer.php";
?>
From your comment above I would say this line is to blame:
if(!hook("homefeaturedcol")):
I'm assuming that this is running as well as your new code above it when it's not the homepage
You may also want to have a look at your HTML structure