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.
Related
This is the code for table in Wordpress.I want to add a class to the first element of the loop. How can I do that. produces series of td elements, how can I change the code so that a class is added only to the first td in tr loop.
$table = get_field( 'hosting_plan_table' );
if ( $table ) {
echo '<tbody>';
foreach ( $table['body'] as $tr ) {
echo '<tr>';
foreach ( $tr as $td ) {
echo '<td><span id="dottedunderlinet" class="'.$td['c'].'"> ';
echo $td['c'];
echo '</td>';
}
echo '</tr>';
}
You could do this
if ( $table ) {
echo '<tbody>';
foreach ( $table['body'] as $tr ) {
echo '<tr>';
$class='first';
foreach ( $tr as $td ) {
echo '<td class="'.$class.'"><span id="dottedunderlinet" class="'.$td['c'].'"> ';
echo $td['c'];
echo '</td>';
$class='';
}
echo '</tr>';
}
Have a look at this. I have set up a variable called $i. Within the foreach loop I add 1 to $i. This means that the first time the loop runs then $i is equal to zero. The !$i test is then matched and $class can be set to be the name of the class you want to apply.
$table = get_field( 'hosting_plan_table' );
$i = 0;
if ( $table ) {
echo '<tbody>';
foreach ( $table['body'] as $tr ) {
echo '<tr>';
foreach ( $tr as $td ) {
if(!$i) { $class = 'some-class'; } else { $class = ''; }
echo '<td><span id="dottedunderlinet" class="'.$class.'"> ';
echo $td['c'];
echo '</td>';
}
echo '</tr>';
$i++;
}
You can update your code like this:
$counter = 0;
foreach ( $tr as $td ) {
if($counter == 0){
echo '<td class="my-custom-class-here"><span id="dottedunderlinet" class="'.$td['c'].'"> ';
} else {
echo '<td><span id="dottedunderlinet" class="'.$td['c'].'"> ';
}
echo $td['c'];
echo '</td>';
$counter++;
}
I have some query that extracts data from the database like this:
|17DATE00 |concat(filename, fileextension) |
|-----------|--------------------------------|
|2017-05-30 |filename00000.pdf |
|2017-03-29 |filename00002.doc |
Now for the second column, I have passed the link of the doc, so you can click on it and download it.
This is the way I extract the data
$header = array("17DATE00", "concat(filename, fileextension)");
echo "<thead><tr>";
foreach ($header as $list) {
echo '<th >' . $list . '</th>';
}
echo "</thead></tr>";
foreach ($query as $key => $value) {
foreach ( $value as $a ) {
$url = get_template_directory_uri();
echo '<td>'. htmlspecialchars($a) .' </td>';
}
echo '</tr>';
}
Doing this, both columns get hyperlinked, while I only need the second one.
Anyway to fix this?
Add a counter to you inner loop:
$counter = 0;
foreach ( $value as $a )
{
$url = get_template_directory_uri();
if ($counter == 1)
{
echo '<td>'. htmlspecialchars($a) .' </td>';
}
else
{
echo '<td>'. htmlspecialchars($a) .'</td>';
}
$counter++;
}
You should print the link only if $key == "concat(filename, fileextension)"
I have a table in the database named 'transactions'. I want to list out the values from this table. The result should be displayed in HTML table format. The rows in the resulted table should be grouped as per the amount.There is a column named 'amount' in the 'transactions' table.
Here is my code:
$s1 = DB::table('transactions')
->select(DB::raw("GROUP_CONCAT(selected_seats SEPARATOR '') as selected_seats"),'userid','amount','show_id')
->where("show_id","=",$s)
->groupBy('userid')
->groupBy('amount')
->orderBy('userid','ASC')
->orderBy('amount', 'DESC')
->get();
I am retrieving the values from $s1 variable through loop.
Following is the output:
and i want the result like this:
Please click on the links given above. I am new to this forum so its not allowing me to add images in the question. Kindly help.
Here is the entire code:
if($s1 != null)
{
echo "<div class='panel-body'>";
echo "<table class='table table-responsive'>"; $c = 1;
echo "<th>Drama Title</th>";
echo "<th>Show Date</th>";
echo "<th>Seat booked</th>";
echo "<th>Amount</th>";
echo "<th>User</th>";
for($i=0;$i<count($s1);$i++)
{
echo "<tr><td>".$shows1[0]->show_title."</td>";
echo "<td>".$shows[0]->show_date."</td>";
echo "<td>";
echo $s1[$i]->selected_seats;
echo "</td>";
/*echo $s1[$i]->userid."<br/>";
echo $s1[$i]->amount."<br/>";*/
$transactions = DB::table('transactions')->where('userid',$s1[$i]->userid)->where('show_id',$s1[$i]->show_id)->get();
//var_dump($transactions);
$total_amount = 0;
//echo "<pre>Users<br/>"; var_dump($transactions);
foreach ($transactions as $transaction)
{
//echo "userid ".$s1[$i]->userid." "."show id: ".$transaction->show_id." "."<br/>";
// echo "amount: ".$transaction->amount." ";
$amount = $transaction->amount;
$total_amount = $total_amount + $amount; //echo $amount."<br/>";
$c = $c+1;
//echo "no. of seats:".$c;
$users = DB::table('users')->where('id',$s1[$i]->userid)->get();
}
echo "<td>".$total_amount."</td>";
//echo $s1[$i]->userid."<br/>";
//echo "<td>".$users[0]->name."</td>";
//echo "<pre>"; var_dump($users);
echo "</td>";
if(isset($users[0]))
{
//echo "values are set";
echo "<td>".$users[0]->name."</td></tr>";
}
else
{
//echo "null value";
continue;
}
}
/*echo $shows[0]->show_date."<br/>";
echo $shows[0]->show_title;*/
//echo "<pre>"; var_dump($s1);
//echo "<td>".$users[0]->name."</td>";
//echo "</tr>";
echo "</table>";
echo "</div>";
?>
}
else
{
echo "No records found";
}
Easiest way I think is calculate amounts in the loop you are printing data or readying data to send to a view. Since your data sorted by user_id, you always can change amount variable in the loop when user_id is changing. You can use count(explode($seat_variable)) to get number of seats in a single run of the loop. Look at the example code below.
$num_seat = 0; $amount = 0; $running_user_id = -1;
foreach ($row as $entry) {
...
if ($running_user_id != $entry['user_id']) { // check if the same user
$running_user_id = $entry['user_id'];
$num_seat = 0; $amount = 0; // resetting variable values for seperate user.
}
$num_seat += count(explode($entry['selected_seats']));
$amount += $entry['amount'];
...
}
And I assume you have missing data like emails in the query.
Code update after questioner added his code.
if($s1 != null) {
echo "<div class='panel-body'>";
echo "<table class='table table-responsive'>"; $c = 1;
echo "<tr>";
echo "<th>Drama Title</th>";
echo "<th>Show Date</th>";
echo "<th>Seat booked</th>";
echo "<th>Amount</th>";
// echo "<th>User</th>";
echo "</tr>";
$category = ""; $num_seats = 0;
for ($i=0; $i<count($s1); $i++) {
if ($category != $amount) {
if ($i > 0) { // print totals
echo "<tr>
<td colspan='3' align='right'>Total</td>
<td>".$num_seats."</td>
<td>".($num_seats * $amount)."</td>
</tr>";
echo "<tr><td colspan='5'> </td></tr>"; // empty row after totals printed
$num_seats = 0; //resetting number of seats per category
}
echo "<tr><td colspan='5'><h2>Category : ".$amount."</h2></td></tr>"; // printing category line in the given table
$category = $amount; // this logic is to prevent category line printing for each row
}
$transactions = DB::table('transactions')->where('userid',$s1[$i]->userid)->where('show_id',$s1[$i]->show_id)->get();
echo "<tr>";
$users = DB::table('users')->where('id', $s1[$i]->userid)->get();
// Check below values are correct or not
echo "<td>".$users[0]->name."</td>";
echo "<td>".$s1[$i]->userid."</td>";
echo "<td>".$s1[$i]->email."</td>"; // get user's email property here
echo "<td>".$s1[$i]->selected_seats."</td>";
$num_seats += count(explode(',', $s1[$i]->selected_seats));
echo "<td> </td></tr>"; // empty colomn for amount and the row end
}
echo "</table>";
echo "</div>";
}
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
}
I have this while loop within another while loop in my PHP:
$selecty = mysql_query("SELECT * FROM followers WHERE userid='".$_SESSION['id']."'");
$rowsy = mysql_num_rows($selecty);
echo '<td>'. $table["username"]. '</td>';
echo '<td>';
while ($tables = mysql_fetch_assoc($selecty)) {
if($tables['followerid']!=$table['id']) {
echo ''.'';
} else {
echo ''.'';
}
}
echo '</td>';
echo "<tr>";
This is more of a logic question and whether or not a nested while loop is the right way to do it. What I'm trying to say is if the 'followerid' from 'user followers table' is not the same as the 'id' from users table (which is from the previous loop) - echo the follow button, else echo the following button.
This is working file while I have data in the followers table but If I don't nothing shows (as there are no rows) - How could I implement this in my PHP? So also if there are no rows in 'followers table' echo follow button?
you can try do it like that
$selecty = mysql_query("SELECT * FROM followers WHERE userid='".$_SESSION['id']."'");
$rowsy = mysql_num_rows($selecty);
echo '<td>'. $table["username"]. '</td>';
echo '<td>';
while ($tables = mysql_fetch_assoc($selecty)) {
if($tables['followerid']!=$table['id'] and $tables['followerid'] != '') {
echo '';
} else if($tables['followerid'] =$table['id'] and $tables['followerid'] !='') {
echo '';
} else {
echo what you like here when $tables['followerid'] = ''
}
}
echo '</td>';
echo "<tr>";
edit
class="follow">'.'</a>'
^------------you dont have to make point and single quotes here
$selecty = mysql_query("SELECT * FROM followers WHERE userid='".$_SESSION['id']."'");
$rowsy = mysql_num_rows($selecty);
echo '<table><tr>';
echo '<td>'. $table["username"]. '</td></tr>';
if ($tables['followerid'] !== ''){
while ($tables = mysql_fetch_assoc($selecty)) {
echo '<tr><td>';
if($tables['followerid']!=$table['id'] and $tables['followerid'] != '') {
echo '</td></tr>';
} else if($tables['followerid'] =$table['id'] and $tables['followerid'] !='') {
echo '</td></tr>';
} else {
echo "what you like here </td></tr>";
}
}
}
else {
echo "do your code here " ;
}
echo "</table>";
Put a boolean (FALSE) at the start of the 'followers' loop such that if it gets crossed make it TRUE. If you get outside the loop and it's still FALSE then add the button anyway.
$trip = FALSE;
while ($tables = mysql_fetch_assoc($selecty)) {
if($tables['followerid']!=$table['id']) {
echo ''.'';
} else {
$trip = TRUE;
echo ''.'';
}
}
if( !$trip ) echo '<a href="#" data-userid="'.$_SESSION['id'].'" class="follow">'.'</a