Pagination for SESSION Arrays Won't Stop After Arrays are Finished - php

I have a PHP Page that displays all of my SESSION's arrays using pagination. The pagination displays ten arrays a page. Currently, my session is holding eleven arrays. My problem is that when I go to the second pagination page which contains my eleventh array, it keeps displaying more arrays that are empty. The pagination keeps going on and on, until a million probably. I would like it to end right at the eleventh array preferably. If for example there was twelve arrays I would like it to end and stop paginating at the twelfth array. Here is an image of my problem:
Here is my full PHP page code:
<?
session_start();//start session for this page
include_once("config.php");
//instantiate variables
$currentpage = isset($_GET['pagenum']) ? (integer)$_GET['pagenum'] : 0;
$numperpage = 10; //number of records per page
$numofpages = count($_SESSION['products'])/$numperpage; //total num of pages
$first = 0; //first page
$last = $numofpages;
if($currentpage==0){ //which page is previous
$previous = 0; //if very first page then previous is same page
}else{
$previous = $currentpage-1;
}
if($currentpage==$last-1){//which page is last
$next = $currentpage;
}else{
$next = $currentpage+1;
}
echo '<form method="post" action="PAYMENT-GATEWAY">';
echo '<ul>';
$cart_items = 0;
$cart_itm = $_SESSION['products'];
for($x=($currentpage*10);$x<(($currentpage*10)+10);$x++){ //output data
$product_code = $cart_itm[$x]["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);
if ($obj) {
echo ($x+1)." ".$cart_itm[$x]["code"]."<br>";
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[$x]["qty"].'</div>';
echo '<div>'.$obj->product_desc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm[$x]["price"]*$cart_itm[$x]["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[$x]["qty"].'" />';
$cart_items ++;
} else {
break; //if no more results, break the while loop
}
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '</span>';
echo '</form>';
echo 'Checkout';
echo "<a href='page.php?pagenum=".$previous."'>Previous</a> <a href='page.php?pagenum=".$next."'>Next</a>"; //hyperlinks controls
?>
And here is my config.php page's full code:
<?php
$mysqli = mssql_connect('gdm','Ga','Rda!');
$objConnectee = mssql_select_db('Gdg',$mysqli );
?>
If anyone can tell me how I can fix this problem it would be greatly appreciated. Thank you for any help.

mssql_fetch_object returns FALSE if there are no more results, so you could stop execution with an if statement:
$obj = mssql_fetch_object($results);
if ($obj) {
echo '<li class="cart-itm">';
//etc... as before all the way down to
$cart_items ++;
} else {
break; //if no more results, break the for loop
}

Related

php shopping cart deleting an item

I am trying to build a shopping cart for a PHP project, however, I have ran into a problem. When I add items to the cart session, I have them displayed in a cart summary.
Item 1 Item 2 Item 3
Whenever I delete an item, the other items below it deletes.
For example, if I delete Item 2 then Item 3 deletes, as well.
If I delete
Item 1,
Items 2 and 3 deletes, too.
update-cart.php
<code>
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"]))
{
$prod_id = $_GET["removep"];
$return_url = base64_decode($_GET["return_url"]);
foreach($_SESSION["products"] as $cart_itm)
{
if($cart_itm["prod_id"]!=$prod_id)
{
$products[] = array('prod_name'=>$cart_itm["prod_name"],'prod_id'=>$cart_itm["prod_id"], 'prod_price'=>$cart_itm["prod_price"], 'prod_percent'=>$cart_itm["prod_percent"], 'prod_qty'=>$cart_itm["prod_qty"]);
}
else
{
$_SESSION["products"] = $products;
}
}
header('Location:'.$return_url);
}
</code>
widget_summary.php
<code>
if(isset($_SESSION['products']))
{
$total = 0;
echo '<ul>';
foreach ($_SESSION["products"] as $cart_itm)
{
$new_price = discount($cart_itm["prod_price"], $cart_itm["prod_percent"]);
echo '<table class="cart-items">';
echo '<tr>';
echo '<td>'.$cart_itm["prod_name"].'</td>';
echo '<td><span class="remove-item right">×</span></td>';
echo '</tr>';
echo '<tr>';
echo '<td id="qty">Qty: '.$cart_itm["prod_qty"].' × $'.$new_price.' = </td>';
$sub = $cart_itm["prod_qty"] * $new_price;
echo '<td class="right subtotal">$'.number_format($sub,2).'</td>';
echo '</tr>';
echo '</table>';
$subtotal = ($new_price*$cart_itm["prod_qty"]);
$total = number_format($total + $subtotal, 2);
}
echo '<table class="tbl-summary-footer">';
echo '<tr>';
echo '<td> Total </td>';
echo '<td><span class="price_now right"><strong>$'.$total.'</strong> </span></td>';
echo '</tr>';
echo '<tr>';
echo '<td><span class="empty-cart">Clear Cart</span></td>';
echo '<td><span class="right">Check-out!</span></td>';
echo '</tr>';
echo '</table>';
echo '</ul>';
}
else
{
echo 'Cart is empty.';
}
</code>
Declare $products before the foreach loop.
You will need to set the session key 'products' after the loop.

Insert array values into mysql database

The variables are being posted from a previous page through array values.
when I print_r($values) I get the whole value on this array including the numerical values of the array ex: array[0], array[1] ..etc.
Please can some tell me what I am doing wrong. the implode function was not used because the values are passed from a cart page though session variables.
First part of code below:
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<form method="post" action="process.php">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm)
{
$product_code = $cart_itm["code"];
$results = $mysqli->query("SELECT Title,Description,Price FROM main_menu WHERE MenuID='$product_code' LIMIT 1");
$obj = $results->fetch_object();
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->Title.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->Description.'</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->Title.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->Description.'" />';
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 '<input name=\'submit\' type="submit" value="Complete Order" style=\"width:150px;background:#333;color:#ffcc33;height:30px;\" />';
echo '</span>';
echo '</form>';
}else{
echo 'No items added';
}
?>
Second part:
Try $post and the table name in the given function and use mysql_real_escape_string() to avoid any possibility of the SQL Injection
form.php
<?php
include ('func_curd.php') ;
if($_POST['hiddenfieldinfo']=='ok')
{
$r=insert_your_table_name($_POST);
if($r==true)
{
header('Location:'.get_full_url()); /* to redirect the form to the same page after successful submission*/
}
}
?>
func_curd.php
<?php
function insert_your_table_name($post)
{
unset($post['hiddenfieldinfo']);
/* Here I am unsetting this value as it is hidden field
in the form , which I am using as form submission check and
is not in database column, apart form auto-increment in database
that is id, you have to maek sure all the post value and column
name matches with case-sensitivities */
$u = insert('your_table_name', $post);
$r=is_numeric($u)? true : false ;
return $r;
}
function insert($table, $values){
$query="INSERT INTO `$table` ";
$column='(';
$val=' (';
$count=count($values);
$mk=1;
foreach ($values as $key=>$value)
{
$value=mysql_real_escape_string($value);
if ($mk==$count)
{
$column .= '`'.$key.'`';
$val .= "'".$value."'";
}
else
{
$column .= '`'.$key.'`, ';
$val .= "'".$value."', ";
}
$mk++;
}
$column .=') ';
$val .=')';
$query=$query.$column.'VALUES'.$val;
$Q=mysql_query($query);
if(mysql_error())
{
return print(mysql_error());
}
else
{
$insert_id=mysql_insert_id();
return $insert_id;
}
}
?>
try this one:
<?php
require_once('config/connect.php');
$item_name = strip_tags($_POST['item_name']);
$item_code = strip_tags($_POST['item_code']);
$item_desc = strip_tags($_POST['item_desc']);
$item_qty = strip_tags($_POST['qty']);
$price = strip_tags($_POST['price']);
$fields = "item_name, item_code, item_desc, price,qty";
$query = "INSERT INTO `x` SET ";
$i = 0;
foreach( $fields as $fieldname )
{
if ( $i > 0 )
$query .= ", ";
$val = strip_tags($_POST[$fieldname]);
$query .= "`" . $fieldname . "` = '" . $val . "'"
$i++
}
$query_result = mysql_query($query);
echo" Record saved";
print_r ( $query );
?>
There are certain syntax errors in your code like not closed foreach etc. whihc I did skip.
As a recommendation: code like this is disclosing the database structure to everyone on the internet - form field names = database col names. This is generally a bad idea.
Better is a kind of mapping table:
$fields = array (
'myFormName' => 'mySqlName',
....
foreach( $fields as $fieldname => $sqlame)
{
if ( $i > 0 )
$query .= ", ";
$val = strip_tags($_POST[$fieldname]);
$query .= "`" . $sqlname. "` = '" . $val . "'"
....
which also will make the form more independent from the underlying data structures.

While loop : get first div to add active class

i want to add active class in while loop first div.
but its not working
$ban_sql = mysql_query("SELECT * FROM banners");
while ($row = mysql_fetch_assoc($ban_sql)){
echo '<div class="item ';
if($row <= 1) {
echo 'active ">';
}
else
{
echo '">';
}
echo '<img src="'.$row['banner_img'].'"/> </div>';
}
This should do the trick:
$ban_sql = mysql_query("SELECT * FROM banners");
$count = 0;
while ($row = mysql_fetch_assoc($ban_sql)){
echo '<div class="item ';
if($count == 0) {
echo 'active ">';
}
else
{
echo '">';
}
echo '<img src="'.$row['banner_img'].'"/> </div>';
$count++;
}
$row will contain a MySQL rowset so you need a separate variable to store the current row iteration count.

php foreach loop issue in IE11

I have very weird issue with php foreach loop in IE 11. In FF, Chrome, Opera, Safari, IE 7 8 9 10 Foreach loop works fine.
I used for() loop for dummy text it works fine in IE 11. But i don't know how to call arrays in for or while loop
here is my code.
$img_num4 = 4;
$data_chunks = array_chunk($wp_images, $num_img);
echo '<ul id="id1">';
foreach ($data_chunks as $data_chunk) {
echo '<li class="id2">';
foreach($data_chunk as $data) {
if($data['image_links_to'])
echo '<a href="'.$data['image_links_to'].'" '.$new_window.'>';
echo '<img src="'.$data['file_url'].'" class="logo-img" alt="" />';
if($data['image_links_to'])
echo '</a>';
}
echo '</li>';
}
echo '</ul>';
I don't know why foreach loop not working in IE 11 only. Any Suggestions.
I also try this:
$img_num4 = 4;
$data_chunks = array_chunk($wp_images, $num_img);
echo '<ul id="id1">';
for($i=1; $i<=10; $i++){
echo '<li>'.$i.'</li>';
}
/*foreach ($data_chunks as $data_chunk) {
echo '<li class="slide">';
foreach($data_chunk as $data) {
if($data['image_links_to'])
echo '<a href="'.$data['image_links_to'].'" '.$new_window.'>';
echo '<img src="'.$data['file_url'].'" class="logo-img" alt="" />';
if($data['image_links_to'])
echo '</a>';
}
echo '</li>';
}*/
echo '</ul>';
It shows me correct data in IE 11. But foreach loop not work
please tell me how can i call arrays in for or while loop
With a for loop it should be like :
$img_num4 = 4;
$data_chunks = array_chunk($wp_images, $num_img);
echo '<ul id="id1">';
$len = $data_chunks.lenght;
for ($i = 0; $i < $len; $i++) {
$data_chunk = $data_chunks[$i];
echo '<li class="id2">';
$len2 = $data_chunk.lenght;
for ($j = 0; $j < $len2; $j++) {
$data = $data_chunk[$j];
if($data['image_links_to']) {
echo '<a href="'.$data['image_links_to'].'" '.$new_window.'>';
}
echo '<img src="'.$data['file_url'].'" class="logo-img" alt="" />';
if($data['image_links_to']) {
echo '</a>';
}
}
echo '</li>';
}
echo '</ul>';
a while loop is not so useful here.
As metionned in comments, php's an html preprocessor so it does not need any browser to work. Maybe you should look on the html source in your IE11 browser to see what is buggy.
MAYBE (and that's an important part of the sentence) IE11 doesn't display <li> if it does not contains any text. Here you only put an <img> (sometimes with a link).
You should try replacing img tag with text in your foreach loop.
Apolo

how to increment CSS ID using PHP programmatically

how can i increment my css ID using php programmatically?
foreach ($query_cat->result() as $row_cat)
{
$row_cat_id = $row_cat->id;
echo '<div class="product-wrapper">';
echo '<div id="product-header" class="product-header">';
echo $row_cat->title;
echo '</div>';
echo '</div>';
$query_prod = $this->db->get_where('products', array('category_id'=>$row_cat_id));
foreach ($query_prod->result() as $row_prod)
{
$row_prod_id = $row_prod->id;
echo '<div id="product-contents" class="product-contents">';
echo $row_prod->title.' '.$row_prod->id;
echo '</div>';
}
}
what i want to happen is to increment the id product-header and product-contents depending on the numbers of rows generated
something like this
product-header1, product-header2, product-header3....
product-contents1, product-contents2, product-contents3....
thanks!
Just initialise an incremental variable before the foreach.
$i = $j = 0;
foreach ($query_cat->result() as $row_cat) {
$i++;
$row_cat_id = $row_cat->id;
echo '<div class="product-wrapper">';
echo '<div id="product-header'.$i.'" class="product-header">';
...
foreach ($query_prod->result() as $row_prod) {
$j++;
$row_prod_id = $row_prod->id;
echo '<div id="product-contents'.$j.'" class="product-contents">';
...
}
}
$i = $j = 1;
foreach (...) {
printf('<div id="product-header-%u" class="product-header">', $i++);
foreach (...) {
printf('<div id="product-contents-%u" class="product-contents">', $j++);
}
}

Categories