SESSION Array Foreach Loop is not Working on PHP Page - php

I have a PHP page that retrieves the arrays in my $_SESSION['products'] session. Each array in that session is a product added by the user to their "shopping cart". Currently my session has eleven arrays meaning I have added eleven products to the cart. I am now trying to display the arrays on my view_cart.php page, and paginate them by ten. Basically I would like the page to show the first ten arrays then create a new page to display the last one. Right now, I believe the code is set up well and has potential to paginate the arrays, but only one array is displayed on the page.
For example, when I run the page on my live website this is what gets displayed:
×
(Code :1)
Qty : 1
Total : 0
Checkout
Here is my full PHP code for the view_cart.php page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
session_start();
include_once("config.php");
$objConnect = mssql_connect('gbdca','Gdca','Rdca');
$objDB = mssql_select_db('Gdca',$objConnect );
$strSQL = "SELECT * FROM products WHERE 1=1 ".$cheack." ORDER BY id ASC";
$objQuery = mssql_query($strSQL) or die ("Error Query [".$strSQL."]");
$Num_Rows = mssql_num_rows($objQuery);
$Per_Page = 10; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$Page_End = $Per_Page * $Page;
IF ($Page_End > $Num_Rows)
{
$Page_End = $Num_Rows;
}
?>
<?php
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<form method="post" action="PAYMENT-GATEWAY">';
echo '<ul>';
$cart_items = 0;
$i = 0;
foreach ($_SESSION['products'] as $cart_itm)
{
if(++$i > 10) break;
$product_code = $cart_itm["code"];
$queryy = "SELECT TOP 1 product_name,product_desc, price FROM products WHERE product_code='$product_code'";
$results = mssql_query($queryy, $mysqli);
$obj = mssql_fetch_object($results);
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-price">'.$currency.$obj->price.'</div>';
echo '<div class="product-info">';
echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->product_desc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->product_desc.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '</span>';
echo '</form>';
echo 'Checkout';
}
?>
</body>
</html>
Here is my full config.php page's code:
<?php
$mysqli = mssql_connect('gdf','Gdfac','Rdcfga');
$objConnectee = mssql_select_db('Gdab',$mysqli );
?>
Thank you for any help. All help is greatly appreciated.

The reason is because
foreach ($_SESSION['products'] as $cart_itm)
if(++$i > 10) break;
{
this will run the break loop 10 times then run a code block once
should be
foreach ($_SESSION['products'] as $cart_itm)
{
if(++$i > 10) break;
this is will run the code block 10 times
it is the "run one line when there is no curly brace" feature of php.

Related

How to change Pagination from 'per page' to only first and last pages?

i have a code for my table pagination.
but now i have a problem. the pagination is showing EVERY page. but i got over 900 pages.
ALSO: i need to use PDO
i want the pagination to work like this:
Image
i dont know how to make this in my already excisting code:
$per_page_html = '';
$page = 1;
$start=0;
if(!empty($_POST["page"])) {
$page = $_POST["page"];
$start=($page-1) * ROW_PER_PAGE;
}
$limit=" limit " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $oConn->prepare($sql);
$pagination_statement->execute();
$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
$per_page_html .= "<div style='text-align:center;margin:20px 0px;'>";
$page_count=ceil($row_count/ROW_PER_PAGE);
if($page_count>1) {
for($i=1;$i<=$page_count;$i++){
if($i==$page){
$per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page current" />';
} else {
$per_page_html .= '<input type="submit" name="page" value="' . $i . '" class="btn-page" />';
}
}
}
$per_page_html .= "</div>";
}
$query = $sql.$limit;
$pdo_statement = $oConn->prepare($query);
$pdo_statement->execute();
$result = $pdo_statement->fetchAll();
I dont see your table and your query in your question so I will give 2 complete examples tested on my demo site, you need to change it to your own variables.
Solution 1.
Here is the example pagination for items belong to a category, for simple pagination :
$perpage = "3";
//This limit of the page to show on each page
$n_stmt = $pdo->prepare("SELECT * FROM categories");
$n_stmt->execute();
$total_posts = $n_stmt->rowCount();
$total_pages = ceil($total_posts/$perpage);
$page = !empty($_GET['page']) && $_GET['page'] ? (int) $_GET['page'] : 1;
if($page < 1) $page = 1;
if($page > $total_pages) $page = $total_pages;
$limit = ($page - 1) * $perpage;
$pag_limit = 10;
$stmt = $pdo->prepare("SELECT * FROM categories ORDER BY created DESC LIMIT :limit, :perpage");
$stmt->bindValue(":limit",$limit, PDO::PARAM_INT);
$stmt->bindValue(":perpage",$perpage, PDO::PARAM_INT);
$stmt->execute();
while($news = $stmt->fetch(PDO::FETCH_ASSOC)){
// Do what ever you want here
}
And pagination:
<div class="pagination">
<?php if($page >1){?>
First
Preview
<?php } for($i = $page - $pag_limit; $i < $page + $pag_limit + 1; $i++){
if($i > 0 and $i <= $total_pages){
if($i == $page){?>
<?php echo $i;?>
<?php }else{?>
<?php echo $i;?>
<?php
}
}
?>
<?php } ?>
<?php if($page != $total_pages){?>
next
Last
<?php } ?>
</div>
Solution 2.
Here is pagination for search result with your codes, as I said this code works on my demo site you need to change your own variables and its in pdo:
define("ROW_PER_PAGE",10);
//this goes on top of your page
require_once("db.php");
$search_keyword = '';
if(!empty($_POST['search']['keyword'])) {
$search_keyword = htmlspecialchars(strip_tags($_POST["search"]["keyword"]), ENT_QUOTES);
}
$sql = 'SELECT * FROM posts WHERE title LIKE :keyword OR descriptions LIKE :keyword OR subject LIKE :keyword ORDER BY id DESC ';
/* Pagination Code starts */
$per_page_html = '';
$page = 1;
$start=0;
if(!empty($_POST["page"])) {
$page = $_POST["page"];
$start=($page-1) * ROW_PER_PAGE;
}
$limit=" limit " . $start . "," . ROW_PER_PAGE;
$pagination_statement = $pdo->prepare($sql);
$pagination_statement->bindValue(':keyword', '%' . $search_keyword . '%', PDO::PARAM_STR);
$pagination_statement->execute();
$row_count = $pagination_statement->rowCount();
if(!empty($row_count)){
$per_page_html .= "<div class=\"pagination\">";
$page_count=ceil($row_count/ROW_PER_PAGE);
if($page_count>1) {
for($i=1;$i<=$page_count;$i++){
if($i==$page){
$per_page_html .= "<input type=\"submit\" name=\"page\" value=" . $i . " class=\"btn-page current\" />";
} else {
$per_page_html .= "<input type=\"submit\" name=\"page\" value=" . $i . " class=\"btn-page\"/>";
}
}
}
$per_page_html .= "</div>";
}
$query = $sql.$limit;
$pdo_statement = $pdo->prepare($query);
$pdo_statement->bindValue(":keyword", "%" . $search_keyword . "%", PDO::PARAM_STR);
$pdo_statement->execute();
$result = $pdo_statement->fetchAll();
Your html part with pagination at the bottom and your result in form same as you can see
<form name="frmSearch" action="search/" method="post">
<div class="searchf">
<input type="text" name="search[keyword]" class="field" value="<?php echo $search_keyword; ?>" id="keyword" maxlength="25">
<input type="submit" name="submit" class="searchf-btn" value="Ara">
</div>
<?php
if(!empty($result)) {
foreach($result as $row) {
?>
<div class="news_box">
<a href="<?php echo htmlspecialchars($row["news_url"]);?>/" title="<?php echo htmlspecialchars($row["title"]);?>">
<div class="title"><h2><?php echo htmlspecialchars($row["title"]);?></h2></div>
<div class="image">
<img src="images/posts/<?php echo htmlspecialchars($row["img"]);?>" alt="<?php echo htmlspecialchars($row["title"]);?>"/></div>
<div class="spot"><?php echo htmlspecialchars($row["subject"]);?></div>
</a>
</div>
<?php
}
}
?>
<div class="cl"> </div>
//Here is pagination
<?php echo $per_page_html; ?>
</form>
I am using seo urls in demo, you need to set htaccess for links, or change pagination links like so : your_page.php?page=$i.
Both tested on my demo site and working, I used some filtering functions you can remove them.

PHP shopping cart does not work right

My shopping cart does not function right.
If i add one item to the cart it works accordingly, but when i add a second or multiple items, the cart seems act strange...
When adding a second item, the quantity of the second item starts at 2.
The quantity of a newly added item starts with the amount of items pressent in the cart. It also increments with the amount of items in the cart.
After adding a third item, the item is displayed as many times as there are items it the cart...
How can change it to add a single item and only increment by one if the items is existing in the cart?
Thanks in advance!
<?php
require "core.inc.php";
require "connect.inc.php";
?>
<html>
<head>
<meta charset="UTF-8">
<title>Winkelwagen</title>
<link rel="stylesheet" type="text/css" href="winkelwagen.css" />
<link rel="stylesheet" type="text/css" href="topAndMenuHeader.css" />
</head>
<body bgcolor="#8A8B93">
<div id="container">
<?php include "topAndMenuHeader.php"; ?>
<div id="content">
<p class="opmaakTitel">Winkelwagen</p>
<?php
if ( isset($_GET['itemID']) ) {
$itemID = $_GET['itemID'];
$sql = "SELECT * FROM items WHERE id=$itemID";
if ( $query = mysql_query($sql) ) {
$numRows = mysql_num_rows($query);
if ( $numRows == 1 ) {
$artID = mysql_result($query, 0, 'id');
$artNaam = mysql_result($query, 0, 'artNaam');
$artPrijs = mysql_result($query, 0, 'artPrijs');
$artAfbeelding = mysql_result($query, 0, 'artAfbeelding');
$artAantal = 1;
$index = -1;
if ( isset($_SESSION['cart']) ) {
unserialize(serialize($_SESSION['cart']));
for ( $i = 0; $i < count($_SESSION['cart']); $i++ )
{
if ( $_SESSION['cart'][$i]['id'] ==
$_GET['itemID'] ) {
$index = $i;
}
if ( $index == -1 ) {
array_push($_SESSION['cart'],
array('id'=>$artID, 'naam'=>$artNaam, 'prijs'=>$artPrijs,
'afbeelding'=>$artAfbeelding, 'aantal'=>$artAantal));
} else {
$_SESSION['cart'][$index]['aantal']++;
}
}
} else {
$_SESSION['cart'] []=array('id'=>$artID,
'naam'=>$artNaam,'prijs'=>$artPrijs,
'afbeelding'=>$artAfbeelding,'aantal'=>$artAantal);
}
}
}
}
foreach ( $_SESSION['cart'] as $cart ) {
echo '<div id="artikelSpace">';
echo '<div id="artikel">';
echo '<div id="afbeelding">';
echo'<imgsrc="data:image/jpeg;base64,'
.base64_encode($cart['afbeelding']).'" />';
echo '</div>';
echo '<div id="naam">';
echo '<p>'.$cart['naam'].'</p>';
echo '</div>';
echo '<div id="aantal">';
echo '<form action="winkelwagen.php" method="POST">';
echo 'Aantal:';
echo '<input type="text" name="aantal" value="'
.$cart['aantal'].'" style="width: 50px; margin: 0px 20px 0px 20px" />';
echo '<input type="submit" name="wijzigAantal"
value="Wijzig" style="width: 100px;
border-radius: 5px; font-weight: bold;" />';
echo '</form>';
echo '</div>';
echo '<div id="prijs">';
echo '<p>Prijs: €'.($cart['prijs'] * $cart['aantal']).'</p>';
echo '</div>';
echo '<div id="verwijder">';
echo '<ul>';
echo '<li>Verwijder</li>';
echo '</ul>';
echo '</div>';
echo '</div>';
echo '</div>';
}
?>
</div>
</div>
</body>
</html>
You have to initialize the $index variable in each iteration of the loop, like this:
// your code
if ( isset($_SESSION['cart']) ) {
unserialize(serialize($_SESSION['cart']));
for ( $i = 0; $i < count($_SESSION['cart']); $i++ ) {
$index = -1; // initialize $index in each iteration
if ( $_SESSION['cart'][$i]['id'] == $_GET['itemID'] ) {
$index = $i;
}
if ( $index == -1 ) {
array_push($_SESSION['cart'], array('id'=>$artID, 'naam'=>$artNaam, 'prijs'=>$artPrijs, 'afbeelding'=>$artAfbeelding, 'aantal'=>$artAantal));
} else {
$_SESSION['cart'][$index]['aantal']++;
}
}
} else {
$_SESSION['cart'][]=array('id'=>$artID, 'naam'=>$artNaam,'prijs'=>$artPrijs, 'afbeelding'=>$artAfbeelding,'aantal'=>$artAantal);
}
// your code
Sidenote: Don't use mysql_ database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli or PDO extensions instead. And this is why you shouldn't use mysql_ functions.

Migration from MySQL to MySQLi extension

I have a script written in Mysql that just lists people's names. It works fine in mysql but i have been trying to get it to update to mysqli and i got most of it. However, the results are supposed to be paginated. The pagination works fine because there should be 5 pages and thats where it stops....but ALL of the results just show up on every page. Not sure what i am doing...any help would be greatly appreciated....I know it has to do with "mysql_result"
Here is my new code in mysqli:
<?php
include ('paginate.php'); //include of paginat page
$per_page = 10; // number of results to show per page
$result = $con->query("SELECT EmployeeID,FirstName,LastName FROM employee;");
//If Database Error...Print the error and exit
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
//If No Database Error.....Continue
if ($result)
{
// Return the number of rows in result set
$total_results=mysqli_num_rows($result);
//printf("Result set has %d rows.\n",$total_results);
// Free result set
}
//total pages we going to have
$total_pages = ceil($total_results / $per_page);
//if page is setcheck
$show_page='';
if (isset($_GET['page'])) {
$show_page = $_GET['page'];//it will telles the current page
if ($show_page > 0 && $show_page <= $total_pages) {
$start = ($show_page - 1) * $per_page;
$end = $start + $per_page;
} else {
// error - show first set of results
$start = 0;
$end = $per_page;
}
} else {
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
$page = intval(isset($_GET['page']));
$tpages=$total_pages;
if ($page <= 0)
$page = 1;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View All Employees</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="logo">
<img src="../admin/images/logo-thompson-industrial-services.gif" class="text- center"width="259" height="59" />
</div>
</div>
<br />
<div class="row">
<div class="span6 offset3">
<div class="mini-layout">
<?php
$reload = $_SERVER['PHP_SELF'] . "?tpages=" . $tpages;
echo '<div class="pagination"><ul>';
if ($total_pages > 1) {
echo paginate($reload, $show_page, $total_pages);
}
echo "</ul></div>";
// display data in table
echo "<table class='table table-bordered'>";
echo "<thead><tr><th>First Name</th> <th>Last Name</th></tr></thead>";
// loop through results of database query, displaying them in the table
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++) {
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) {
break;
}
while($row = mysqli_fetch_assoc($result)) {
$id = $row['EmployeeID'];
$fname = $row['FirstName'];
$lname = $row['LastName'];
echo "<tr>";
echo '<td class="col-md-4">' .$fname .'</td>';
echo '<td class="col-md-4">' .$lname .'</td>';
echo "</tr>";
}
}
// close table>
echo "</table>";
?>
</div>
</div>
</div>
</div>
</body>
</html>
And here is my original code in mysql:
<?php
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
error_reporting(E_ALL ^ E_DEPRECATED);
include('config.php'); //include of db config file
include ('paginate.php'); //include of paginat page
$per_page = 10; // number of results to show per page
$result = mysql_query("SELECT * FROM employee");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);//total pages we going to have
//-------------if page is setcheck------------------//
$show_page='';
if (isset($_GET['page'])) {
$show_page = $_GET['page']; //it will telles the current page
if ($show_page > 0 && $show_page <= $total_pages) {
$start = ($show_page - 1) * $per_page;
$end = $start + $per_page;
} else {
// error - show first set of results
$start = 0;
$end = $per_page;
}
} else {
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
$page = intval(isset($_GET['page']));
$tpages=$total_pages;
if ($page <= 0)
$page = 1;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View Employees</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<style type="text/css">
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="logo">
<img src="../admin/images/logo-thompson-industrial-services.gif" class="text-center"width="259" height="59" />
</div>
</div>
<br />
<div class="row">
<div class="span6 offset3">
<div class="mini-layout">
<?php
$reload = $_SERVER['PHP_SELF'] . "?tpages=" . $tpages;
echo '<div class="pagination"><ul>';
if ($total_pages > 1) {
echo paginate($reload, $show_page, $total_pages);
}
echo "</ul></div>";
// display data in table
echo "<table class='table table-bordered'>";
echo "<thead><tr><th>First Name</th> <th>Last Name</th></tr></thead>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++) {
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) {
break;
}
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . mysql_result($result, $i, 'FirstName') . '</td>';
echo '<td>' . mysql_result($result, $i, 'LastName') . '</td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
?>
</div>
</div>
</div>
</div>
</body>
</html>
I am doing something wrong here and i cant figure it out....
Any help would be greatly appreciated...
Thanks a lot.
I would also just remove the while statement and use mysqli_data_seek in conjunction with mysqli_fetch_accoc. The MySQLi_data_seek points to the result I need. Check it out:
// display data in table
echo "<table class='table table-bordered'>";
echo "<thead><tr><th>First
Name</th> <th>Last Name</th></tr></thead>";
// loop through results of database query, displaying them in the table
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++) {
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) {
break;
}
//go to the column you want the results
mysqli_data_seek($result, $i);
$row = mysqli_fetch_assoc($result);
// echo out the contents of the row into a table
echo "<tr>";
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['LastName'] . '</td>';
echo "</tr>";
}
}
echo "</table>";
The way you are extracting the query is the problem. Once you enter the while statement it does not leave until all the results are done and then it executes
if ($i == $total_results) {
break;
}
So it never gets a chance to end at $i greater than $total_result. The fix is to include LIMIT and OFFSET in the query. That means you have to fix the pagination page too.
So just run the query again like:
// display data in table
echo "<table class='table table-bordered'>";
echo "<thead><tr><th>First
Name</th> <th>Last Name</th></tr></thead>";
// loop through results of database query, displaying them in the table
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++) {
// run the query again
$sql ="SELECT EmployeeID,FirstName,LastName FROM employee LIMIT $per_page OFFSET $end;
$result = $con->query($sql);
while($row = mysqli_fetch_assoc($result)) {
$id = $row['EmployeeID'];
$fname = $row['FirstName'];
$lname = $row['LastName'];
echo "<tr>";
echo '<td class="col-md-4">' .$fname .'</td>';
echo '<td class="col-md-4">' .$lname .'</td>';
echo "</tr>";
}
}
echo "</table>";

Why am I getting Notice: Trying to get property of non-object error?

I keep getting errors and I don't understand why, I have tried everything I know
The aim is to my final basket and to check out using th pay now function.
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<div id="products-wrapper">
<h1>View Cart</h1>
<div class="view-cart">
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<form method="post" action="paypal-express-checkout/process.php">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm)
{
$product_code = $cart_itm["code"];
$results = $mysqli->query("SELECT product_name,product_description, price FROM products WHERE product_code='$product_code' LIMIT 1");
if( !$results)
die($mysqli->error);
$queryResult = array();
while ($obj = $results->fetch_object())
{
$queryResult[] = $obj->product_name;
}
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-price">'.$currency.$obj['0']->price.'</div>';
echo '<div class="product-info">';
echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->product_desc.'</div>';}
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_price['.$cart_items.']" value="'.$obj->price.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<input type="submit" value="Pay Now" />';
echo '</form>';
echo '<span class="check-out-txt"><strong>Total : '.$currency.$total.'</strong></span>';
?>
</div>
</div>
</body>
</html>
You have a few errors that I can see.
in your while loop, you are fetching all your results, one by one, in the temp var called $obj.
while ($obj = $results->fetch_object())
{
$queryResult[] = $obj->product_name;
}
inside the loop, you can access all the properties of $obj. For example you can get product_name, and that is ok.
But after the last iteration of the loop, $obj will be always null, as you can see in http://php.net/manual/es/mysqli-result.fetch-object.php
And of course, at no point $obj is an array, so:
you shouldnt read $obj as an array, and
you shouldnt read $obj at all after the loop.
For this, when you try
echo '<div class="p-price">'.$currency.$obj['0']->price.'</div>';
you are trying to get the first item of an array that is not an array, so it will fail.
and in
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
or
echo '<input type="hidden" name="item_price['.$cart_items.']" value="'.$obj->price.'" />';
you will always be accesing a null object, so it will also fail.
the solution will be to change your while loop, so it includes all the code below related to one row in the database.
//keep your code until here
while ($obj = $results->fetch_object())
{
// $queryResult[] = $obj->product_name; //probably you dont need this
// } your loop ends here, but it shouldnt
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
//you dont access $obj[0], but $obj
echo '<div class="p-price">'.$currency.$obj->price.'</div>';
echo '<div class="product-info">';
echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->product_desc.'</div>';}
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_price['.$cart_items.']" value="'.$obj->price.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items ++;
}
}//this is the new end of your loop
echo '</ul>';
//from here, your code remains the same
With this, you will solve the problem you are reporting, but probably you will have to check your code carefully since it could contain some other bugs.

How do I not display certain parts of the table from my database?

http://i.stack.imgur.com/5OTgG.png
The image above describes my problem, and provides a visual.
As you can see, I just want to reserve or delete the two spaces on the top-right. How can I achieve this?
This is my current code:
<html>
<head>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("dbname");
$strSQL = "SELECT * FROM album";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 12; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by albumID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
echo"<table border=\"0\" cellspacing=\"1\" cellpadding=\"1\"><tr>";
$intRows = 0;
while($objResult = mysql_fetch_array($objQuery))
{
echo "<td>";
$intRows++;
?>
<center>
<img src="https://s3.amazonaws.com/thumbnails/<?=$objResult["Picture"];?>" height="190" width="190" /></a><br>
<?=$objResult["albumName"];?>
<br>
</center>
<?php
echo"</td>";
if(($intRows)%4==0)
{
echo"</tr>";
}
}
echo"</tr></table>";
?>
<br>
<?php
//DELETED PAGINATION CODE for the sake of simplicity in StackOverflow
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
In your loop, you'd need to put in some conditional statement to break from the default behavior.
while($objResult = mysql_fetch_array($objQuery))
{
if(($intRows)%4==0)
{
echo"<tr>"; // You forgot this.
}
echo "<td>";
$intRows++;
if ($intRows == 3 || $intRows == 4) :
?>
<!-- special cells -->
<?
else:
?>
<center>
<img src="https://s3.amazonaws.com/thumbnails/<?=$objResult["Picture"];?>" height="190" width="190" /></a><br>
<?=$objResult["albumName"];?>
<br>
</center>
<?php
endif;
echo"</td>";
if(($intRows)%4==0)
{
echo"</tr>";
}
}
// You also need this part:
echo ($intRows %4 > 0 ? "</tr>" : "") . "</table>";
Your $intRows variable seems to be counting cells, not rows. So you can simply identify the top right cells by their numbers, which should be 2 and 3. Add this to your loop:
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2 || $cell == 3) {
echo '<td>RESERVED</td>';
} else {
echo '<td>'.$objResult["albumName"].'</td>';
}
$cell++;
}
echo '</tr></table>';

Categories