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.
Related
I am wanting to use 8 images from my database and load them into a HTML Table. I would like to display 4 images per table row, but however when i run my code below, i seem to get all images in one table row. Any help would be great. Thank you in advance.
$count = $get->rowCount();
if ($count > 0)
{
echo '<table id="" class="uiGrid _51mz _1m6c" cellpadding="2" cellspacing="0">';
$i = 0;
while ($r = $get->fetch(\PDO::FETCH_OBJ))
{
$globals = new \Libraries\Helpers\Views\Globals;
if ($i == 0)
{
echo '<tr class="_51mx">';
}
echo '
<td class="_51m-">
<a href="/e/a/'.$r->data_id.'">
<div class="uiScaledImageContainer _f-u2" style="width:74px;height:74px;">
<img class="scaledImageFitWidth img" src="https://gstatic.acfee.org/akamaihd/i/'.$globals->data_image_name($r->data_id).'">
<div class="_3s6x">
<div class="_50f3"></div>
</div>
</div>
</a>
</td>
';
if ($i > 4)
{
$i = 0;
echo '</tr>';
};
$i++;
echo '
<script type="text/javascript">
$("#favs-preloader").hide();
</script>
';
}
echo '</table>';
put this code directly it will works...
echo '<table id="" class="uiGrid _51mz _1m6c" cellpadding="2" cellspacing="0">';
$i = 0;
while ($r = $get->fetch(\PDO::FETCH_OBJ))
{
$globals = new \Libraries\Helpers\Views\Globals;
$i++;
if ($i == 1)
{
echo '<tr class="_51mx">';
}
echo '
<td class="_51m-">
<a href="/e/a/'.$r->data_id.'">
<div class="uiScaledImageContainer _f-u2" style="width:74px;height:74px;">
<img class="scaledImageFitWidth img" src="https://gstatic.acfee.org/akamaihd/i/'.$globals->data_image_name($r->data_id).'">
<div class="_3s6x">
<div class="_50f3"></div>
</div>
</div>
</a>
</td>
';
if ($i >= 4)
{
echo '</tr>';
$i = 0;
};
echo '
<script type="text/javascript">
$("#favs-preloader").hide();
</script>
';
}
echo '</table>';
In your current code, you're verifying if the $i variable is == 0 in order to add a row. But you're always increasing it's value at the end, even after you set it to zero in the if($i > 4)
Change these lines
if ($i > 4)
{
$i = 0;
echo '</tr>';
};
$i++;
To this:
if ($i > 4)
{
$i = 0;
echo '</tr>';
}
else
$i++;
<!DOCTYPE html>
<html lang="en">
<head>
<h1>Table Generator</h1>
</head>
<body>
<center>Refresh</center>
<?php
$rows = (isset($_POST['rows']) ? $_POST['rows'] : null);
$cols = (isset($_POST['cols']) ? $_POST['cols'] : null);
$highlight = (isset($_POST['highlight']) ? $_POST['highlight'] : null);
if ($rows == "")
{
$rows = 10;
}
if ($cols == "")
{
$cols = 10;
}
if ($highlight == "")
{
$highlight = 5;
}
?>
<form method="post">
ROWS <input type="text" name="rows" value = "<?php echo $rows;?>" />
COLUMNS <input type="text" name="cols" value = "<?php echo $cols;?>" />
HIGHLIGHT <input type = "text" name = "highlight" value = "<?php echo $highlight;?>" /><br>
<input type="submit" value="Generate">
</form>
<?php
if(isset($_POST['rows']))
{
$randnumber = rand(0,100);
$rows = $_POST['rows'];
$cols = $_POST['cols'];
$highlight = $_POST['highlight'];
echo '<table border="1" align = "center">';
if (is_numeric($rows) and is_numeric($cols) and is_numeric($highlight))
{
if ($randnumber % 2 == 0)
{
echo '<center>The first number is <div class = "red">even</div></center>';
}
else
{
echo '<center>The first number is <div class = "green">odd</div></center>';
}
for($row = 1; $row <= $rows; $row++)
{
echo '<tr style = "background-color:green">';
for($col = 1; $col <= $cols; $col++)
{
if ($randnumber % $highlight == 0)
{
echo '<td style = "background-color: red">';
echo $randnumber;
$randnumber++;
echo '</td>';
}
else
{
echo '<td>';
echo $randnumber;
$randnumber++;
echo '</td>';
}
}
echo '</tr>';
}
echo '</table>';
}
else
{
echo "<center>Rows / Columns / Highlight must ALL be INTEGER values. Re-enter correct value(s).</center>";
}
echo '<pre><center>';
print_r($_POST);
echo '</center></pre>';
}
?>
<style type ="text/css">
h1 {
color: grey;
text-align:center;
}
form {
text-align: center;
padding-bottom: 20px;
}
a:link {
text-decoration: none;
}
.red {
color: red;
}
.green {
color: green;
}
</style>
</body>
</html>
So. I have this PHP code to generate a table based off the user's input and I recently ran into a problem I cant figure out how to fix.
It was working perfectly fine but now whenever I use the Refresh link it resets the entire page to default (i.e. default textbox values instead of keeping the current ones, removing the table).
So, I have 2 questions. How would I keep the data on refresh (with $_POST being used) and how to display the table with the default values when the page first loads.
Refresh
Clicking it will trigger browser's reload mechanism and you'll be asked to resubmit the form action, it will allow you to keep POST data.
You need to re-create the post if you want to keep the parameters. Can be done pretty eaily by looping thru the array.
<form method='POST' id='refresh' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<?php foreach($_POST as $k=>$v): ?>
<input type='hidden' name='<?php echo $k; ?>' value='<?php echo $v; ?>' />
<?php endforeach; ?>
<a href='#' onclick='document.getElementById("refresh").submit(); return false;'>refresh</a>
</form>
Note: This is a little longer than the other answer, but will not prompt to resend post data.
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.
i'm developing a php project in which i'm getting the list from the database and i need to display this data in html in 3 columns and 10 rows and add a button "more" in the end
<?php foreach ($items as $item) { ?>
<ul>
<li><a href="<?php echo $item['href']; ?>" >
<?php echo $item['name']; ?></a></li>
</ul>
<?php } ?>
I want it to be displayed as-
item1 item2 item3
item4 item5 item6
.
.
.
.
Maximum 10 rows
last row will be
item item "more" - only if there are more items in the list
"more" is just a link which will take me to some other page
Thanks for any help.
Add display:inline to li and use pseudo class to break it
ul{
margin:0
}
li{
display:inline
}
li:nth-child(3n):after {
content:"\A";
white-space:pre;
}
Script (To display more link)
$('#moreli').toggle($("li").size() > 6);
This enables the more link after 6 list items, you can change the count in the script.
Note: Reduce the list items to check the effect
DEMO UPDATED
<style>
.row {
width:100%;
float:left;
}
.item {
width:100px;
float:left;
}
</style>
<?php
//*** your array of items
$items = array("item1", "item2", "item3", "item4","item5", "item6", "item7", "item8", "item9", "item10");
$numItems = sizeof($items);
//*** max number of rows
$maxRows = 10;
$maxItems = 3 * $maxRows;
echo '<div class="row">';
for ($i=0; $i<$numItems;$i++) {
echo '<div class="item">'.$items[$i].'</div>';
if (($i+1) % 3 == 0) {
//*** if divisible by 3, close row
echo '</div><div class="row">';
}
if ($i == $numItems) {
//*** last item reached, close div
echo '</div>';
}
if ($i+1 >= $maxItems ) {
//*** max 10 row, add more button.
echo '</div><input type="submit" value="Add More">';
return;
}
}
?>
Try to use this:
<?php
$count=0;
foreach ($items as $item) { ?>
<ul class="col3">
<li>
<?php if($count > 9) { ?>
More</li></ul>
<?php break;
} else{ ?>
<a href="<?php echo $item['href']; ?>" >
<?php echo $item['name'];
$count=$count+1;
?></a>
<?php } ?>
</li>
</ul>
<?php } ?>
and following css for it
.col3
{
margin-left:-3%;
}
.cols3 li
{
width:30%;
margin-left:3%;
display:inline-block;
vertical-align:top;
}
.cols3 li a
{
display:block;
}
i have pagination system on my echo results however, the page numbers are being echo'ed underneath eachother
e.g.
1
2 3 4 5
this is my code:
for($i=0;$i < $count1;$i=$i+$limit)
{
if($i <> $start)
{
echo "<a href='view.php?search=$search&start=$i&limit=$limit&price=$price&category=$category'><font face='Verdana' size='2'><b> $l </b></font></a> ";
}
else
{
echo "<center><font face='Verdana' size='4' color=#2E9AFE ><b> $l </b></font></center>";
}
MODIFIED CODE:
$i=0;
$l=1;
echo "<p align='left'>";
for($i=0;$i < $count1;$i=$i+$limit)
{
if($i <> $start)
{
echo '$i';
}
else
{
echo '<span class="current">$i</span>';
}
$l=$l+1;
}
echo "</p>";
}
<?php for($i=0;$i < $count1;$i=$i+$limit): ?>
<?php if($i <> $start): ?>
<a href="view.php?search=<?php echo $search;?>&start=<?php echo $i;?>&limit=<?php echo $limit;?>&price=<?php echo $price;?>&category=<?php echo $category;?>">
<?php echo $i; ?></a>
<?php else: ?>
<span class="current"><?php echo $i;?></span>
<?php endif; ?>
<?php endfor; ?>
CSS:
a,span.current{font-weight:bold;font-family:Verdana;}
All are inline elements, so they'll stay...inline. Add paddings, text-decoration, colors and whatever in your CSS. I could help you to achieve exactly what you want if you are more clear in your intentions (center?). Stay away from old html and tables :)
Here is another way of doing the above, with a few added extras:
$count1 = 10;
$menu = '';
$link = array(
'search' => ( isset($search) ? $search : $search = '' ),
'start' => ( isset($start) ? $start : $start = 0 ),
'limit' => ( isset($limit) ? $limit : $limit = 1 ),
'price' => ( isset($price) ? $price : $price = '' ),
'category' => ( isset($category) ? $category : $category = '' ),
);
foreach( range(0, $count1, $limit) as $i ) {
$menu .= ( ($link['start'] = $i) == $start ?
'<span class="current">'.$i.'</span>' :
''.$i.''
) . PHP_EOL;
}
echo $menu;
(the above requires php5+)
With regards to neeko's comment, to seperate the $start variable from the text displayed in the link - all you have to do is either introduce another variable that counts up with each loop - or, as we already have the key of the range array, we can use that:
foreach( range(0, $count1, $limit) as $key => $i ) {
$menu .= ( ($link['start'] = $i) == $start ?
'<span class="current">Page'.($key+1).'</span>' :
'Page'.($key+1).''
) . PHP_EOL;
}
I've used $key + 1, because $key will be zero-based (i.e. counting up from Zero) but the +1 just shifts things so we count up from 1 instead.
I think it is because center is a block element which means it won't be inline with the other numbers (but that isn't my specialty so I might be wrong. You could put them in a table.
echo "<table><tr>";
for($i=0;$i < $count1;$i=$i+$limit)
{
echo "<td>";
if($i <> $start)
{
echo "<a href='view.php?search=$search&start=$i&limit=$limit&price=$price&category=$category'><font face='Verdana' size='2'><b> $l </b></font></a> ";
}
else
{
echo "<center><font face='Verdana' size='4' color=#2E9AFE ><b> $l </b></font></center>";
}
echo "</td>";
}
echo "</tr></table>";
Try this:
for($i=0;$i < $count1;$i=$i+$limit)
{
if($i <> $start)
{
echo "<a href='view.php?search=$search&start=$i&limit=$limit&price=$price&category=$category'><div style='font-family: verdana; font-size: 12px; font-weight: bold; float: left; position: relative; padding: 5px; margin-right: 5px;'>$l</div></a>";
}
else
{
echo "<div style='font-family: verdana; font-size: 14px; font-weight: bold; float: left; position: relative; color: #2E9AFE; padding: 5px; margin-right: 5px;'>$l</div>";
}
I have changed your html part of code to display in div elements with float: left and some other css tweaks so now it should be placed in one line...