Think I've done this completely wrong but I am trying to display the values of the items when added to the shopping cart into a table. My code looks like this:
<?php
function minicart() {
foreach($_SESSION as $name => $value) {
if ($value > 0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name) -5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
'<table border = "1">'
'<tr>'
'<td>'<echo $get_row['name'].' x '.$value.' # £'.number_format($get_row['price'], 2).' = £'.number_format($sub, 2).' [-] [+] [Delete]<br />''</tr>';
'</tr>'
'</table>'
}
}
$total += $sub;
}
}
if ($total==0) {
echo "Your cart is empty";
}
else {
echo '<br />Total: £'.number_format($total, 2);
?>
Try this:
function minicart()
{
$items = 0;
$tbl = array();
foreach($_SESSION as $name => $value)
{
if ($value > 0) {
if (substr($name, 0, 5)=='cart_')
{
$id = substr($name, 5, (strlen($name) -5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
$tbl[] = '<table border="1"><thead><tr>'
. '<th>Item</th>'
. '<th>Quantity</th>'
. '<th>Unit Price</th>'
. '<th>SubTotal</th>'
. '<th>Action</th>'
. '</tr></thead><tbody>'
;
while ($get_row = mysql_fetch_assoc($get)) {
$items++;
$sub = $get_row['price'] * $value;
$tbl[] = '<tr>'
. '<td>' . $get_row['name'] . '</td>'
. '<td>' . $value . '</td>'
. '<td>£' . number_format( $get_row['price'], 2 ) . '</td>'
. '<td>$pound;' . number_format( $sub, 2) . '</td>'
. '<td>'
. ' [-] '
. ' [+] '
. ' [Delete]'
. '</td>'
. '</tr>'
;
}
$tbl[] = '</tbody>';
}
$total += $sub;
}
}
if ($items==0)
{
echo "Your cart is empty";
}
else
{
$tbl[] = '<tfoot><tr>'
. '<td colspan="3" style="text-align:right; font-weight:bold">Total:</td>'
. '<td>£' . number_format($total, 2) . '</td></tr></tfoot></table>';
echo implode( "\n", $tbl );
}
}
I changed the logic so that if the item count is zero, it displays the "empty cart" message, allowing for zero-cost items.
I tried to re write your table to correct format:
echo '<table border = "1">';
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo '
<tr>
<td>'.
$get_row['name'].' x '.$value.' # £'.number_format($get_row['price'], 2).' = £'.number_format($sub, 2).'
[-]
[+]
[Delete]<br />
</td>
</tr>
';
}
echo '</table>';
Please see PHP Strings
I think you want to replace the if-statement with the following.
This will give you 1 table with a row per item, probably what you're looking for.
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name) -5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
echo '<table border = "1">';
echo '<tr>';
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo '<td>';
echo $get_row['name'].' x '.$value.' # £';
echo number_format($get_row['price'], 2).' = £';
echo number_format($sub, 2);
echo '[-] ';
echo '[+] ';
echo '[Delete]<br />';
}
echo'</tr>';
echo'</table>';
}
Related
I have a MySQL table of results of collected responses on a form that I want to output in a table.
The user rates certain variables such as Sleep from good (1) to bad (7) and each users results are on each row.
I did that successfully, but to make it more readable I want to colour code the scores based on score.
E.g., if you score 2 or below the table cell should be green, and if you score 6 or above it is coloured red.
There are 5 different variables being rated so not sure if the method I am using would work or if something more suitable.
$sql = "SELECT * FROM Responses";
$result = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($result))
{
echo '<tr>';
if($row['Sleep'] <= 2)
{
echo "<td style='background-color: green;'>" . $row['Sleep'] . "</td>";
}
elseif ($row['Sleep'] >= 6)
{
echo "<td style='background-color: red;'>" . $row['Sleep'] . "</td>";
}
else
{
echo "<td>" . $row['Sleep'] . "</td>";
}
echo '</tr>';
}
No output
Maybe so
function getColor($number)
{
if ($numner <= 2)
return 'green';
else if ($numner > 2 && $var < 6)
return 'black';
else if ($number >= 6)
return 'red';
}
$sql = "SELECT * FROM Responses";
$result = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($result))
{
echo '<tr>';
echo '<td>' . $row["Name"] . '</td>';
echo '<td style="background-color: "' . $getColor($row["Sleep"]) . '">' . $row["Sleep"] . '</td>';
}
You just put your different variables in an array
function getColor($number)
{
if ($number <= 2)
return 'green';
else if ($number > 2 && $number < 6)
return 'none';
else if ($number >= 6)
return 'red';
}
echo "<table>";
while ($row = mysqli_fetch_array($result))
{
//replace var* with your variable
$variables = array("Sleep", "var2", "var3", "var4", "var5");
echo '<tr>';
echo '<td>' . $row["Name"] . '</td>';
$i=0;
while($i<5)
{
$score=$row[$variables[$i]];
echo '<td style="background-color: ' . getColor($score). ';">' . $score . '</td>';
$i++;
}
echo '</tr>';
}
echo "</table>";
The following code is displaying product name in one row and quantity,price and subtotal in new row, how to get all these on same row. Output screenshot as been attached below.
code output
<table class="table table-striped table-condensed">
<tbody>
<?php
$r = 1;
$tax_summary = array();
foreach ($rows as $row) {
if (isset($tax_summary[$row->tax_code])) {
$tax_summary[$row->tax_code]['items'] += $row->quantity;
$tax_summary[$row->tax_code]['tax'] += $row->item_tax;
$tax_summary[$row->tax_code]['amt'] += ($row->quantity * $row->net_unit_price) - $row->item_discount;
} else {
$tax_summary[$row->tax_code]['items'] = $row->quantity;
$tax_summary[$row->tax_code]['tax'] = $row->item_tax;
$tax_summary[$row->tax_code]['amt'] = ($row->quantity * $row->net_unit_price) - $row->item_discount;
$tax_summary[$row->tax_code]['name'] = $row->tax_name;
$tax_summary[$row->tax_code]['code'] = $row->tax_code;
$tax_summary[$row->tax_code]['rate'] = $row->tax_rate;
}
echo '<tr><td colspan="2">#' . $r . ': ' . product_name($row->product_name) . ($row->variant ? ' (' . $row->variant . ')' : '') . '<span class="pull-right">' . $row->tax_code . '</span></td></tr>';
echo '<tr><td>' . $this->sma->formatNumber($row->quantity) . ' x ';
if ($row->item_discount != 0) {
echo '<del>' . $this->sma->formatMoney($row->net_unit_price + ($row->item_discount / $row->quantity) + ($row->item_tax / $row->quantity)) . '</del> ';
}
echo $this->sma->formatMoney($row->net_unit_price + ($row->item_tax / $row->quantity)) . '</td><td class="text-right">' . $this->sma->formatMoney($row->subtotal) . '</td></tr>';
$r++;
}
?>
</tbody>
<tfoot>
<tr>
Try below, but probabbly the formatting will be broken:
<table class="table table-striped table-condensed">
<tbody>
<?php
$r = 1;
$tax_summary = array();
foreach ($rows as $row) {
if (isset($tax_summary[$row->tax_code])) {
$tax_summary[$row->tax_code]['items'] += $row->quantity;
$tax_summary[$row->tax_code]['tax'] += $row->item_tax;
$tax_summary[$row->tax_code]['amt'] += ($row->quantity * $row->net_unit_price) - $row->item_discount;
} else {
$tax_summary[$row->tax_code]['items'] = $row->quantity;
$tax_summary[$row->tax_code]['tax'] = $row->item_tax;
$tax_summary[$row->tax_code]['amt'] = ($row->quantity * $row->net_unit_price) - $row->item_discount;
$tax_summary[$row->tax_code]['name'] = $row->tax_name;
$tax_summary[$row->tax_code]['code'] = $row->tax_code;
$tax_summary[$row->tax_code]['rate'] = $row->tax_rate;
}
echo '<tr><td colspan="2">#' . $r . ': ' . product_name($row->product_name) . ($row->variant ? ' (' . $row->variant . ')' : '') . '<span class="pull-right">' . $row->tax_code . '</span>';
echo '' . $this->sma->formatNumber($row->quantity) . ' x ';
if ($row->item_discount != 0) {
echo '<del>' . $this->sma->formatMoney($row->net_unit_price + ($row->item_discount / $row->quantity) + ($row->item_tax / $row->quantity)) . '</del> ';
}
echo $this->sma->formatMoney($row->net_unit_price + ($row->item_tax / $row->quantity)) . '' . $this->sma->formatMoney($row->subtotal) . '</td></tr>';
$r++;
}
?>
</tbody>
I have a php leaderboard and it works great, and works well with ties. Currently it will number users from 1st to last place (whichever # that is), and if there are ties, it lists them all out with the same number.
For example:
userC 2. userG 3. userA 3. userT 3. userJ 4. userW 5. userP
What I would like is for when there are ties, for the leaderboard to display a "(t)" next to the number, like so: (t) 3. userT
Here is my code, any help is appreciated:
<table cellpadding="4" cellspacing="0" class="table1" width="100%"><caption>
<h2>Leaderboard</h2>
</caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$i = 1;
$tmpScore = 0;
//show place #
foreach($playerTotals as $playerID => $stats) {
if ($tmpScore < $stats[score]) $tmpScore = $stats[score];
//if next lowest score is reached, increase counter
if ($stats[score] < $tmpScore ) $i++;
$pickRatio = $stats[score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($stats[score] / $possibleScoreTotal) * 100), 2) . '%';
//display users/stats
$rowclass = ((($i - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $i . '</b>. ' . $stats[userName] . '</td><td align="center">' . $stats[wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$tmpScore = $stats[score];
}
}
echo ' </div>' . "\n";
?>
</table>
Try this code... hope it will resolve your issue
<table cellpadding="4" cellspacing="0" class="table1" width="100%">
<caption><h2>Leaderboard</h2></caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$j = 1;
$tmpScore = 0;
//show place #
$tieflag=false;
for($i=0; $i<=count($playerTotals)-1; $i++) {
if(($i<count($playerTotals) && $playerTotals[$i][score]==$playerTotals[$i+1][score]) || ($i>0 && $playerTotals[$i][score]==$playerTotals[$i-1][score])) $tieflag=true;
$pickRatio = $$playerTotals[$i][score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($playerTotals[$i][score] / $possibleScoreTotal) * 100), 2) . '%';
$rowclass = ((($j - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . ($tieflag?'(t)'.$j:$j) . '</b>. ' . $playerTotals[$i][userName] . '</td><td align="center">' . $playerTotals[$i][wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$j++;
}
}
echo '</div>'. "\n";
?>
</table>
I'd create a new variable $placeholder. So:
if ( $i != 0 ) {
if ($tmpScore < $stats[score]) {
$tmpScore = $stats[score];
}
if ( $tmpScore == $stats[score] ) {
$placeholder = $i.'(t)';
} else if ($stats[score] < $tmpScore )
$placeholder = $++i;
}
} else {
$placeholder = $++i;
$firstScore = $stats[score];
$tmpScore = $stats[score];
}
Then instead of printing $i print $placeholder
so for the first time through you could do this in the echo:
//It makes more sense if you read it from bottom to top but I put it this way
//so you will not have to keep running through every condition when you will
//only evaluate the first condition most often
if ( $i != 0 && $i != 1 ) {
echo ;//Your normal print
} else if ( $i = 1 && $tmpScore != $firstScore ) {
echo '<b>'; //and the rest of the first line plus second line NOT a tie
} else if ( $i = 1 ) {
echo ' (t)'; //Plus the rest of your first line plus second line TIE
} else {
//This is your first time through the loop and you don't know if it's a tie yet so just
//Print placeholder and then wait to figure out the rest
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $placeholder;
}
I have a web page where i am able to export a .csv file that is readable on excel. The invoice pulls the data from my database to calculate the total and grand total using the following columns:
quantity, packing_price, courier_price
I have noticed that my code doesn't output the correct answer when the prices contains a '£' sound in front of it. Is there a way that i could make this work for both number and currency data types?
CODE:
$output2= "";
$sql2 = mysql_query("
SELECT j.date
, j.order_ref
, j.quantity
, j.packing_price
, j.dispatch_type
, j.courier_price
FROM Jobs j
WHERE j.order_type = 'Retail International'
AND j.confirmed = 'Yes';
");
$columns_total2 = mysql_num_fields($sql2);
$total3 = "Total";
for ($i = 0; $i < $columns_total2; $i++)
{
$heading2 = mysql_field_name($sql2, $i);
$output2 .= '"'.$heading2.'",';
}
$output2 .= $total3;
$output2 .="\n";
$sum2 = 0;
while ($row = mysql_fetch_array($sql2)) {
for ($i = 0; $i < $columns_total2; $i++) {
$output2 .='"'.$row["$i"].'",';
}
$qty2 = $row['quantity'];
$pack_price2 = $row['packing_price'];
$dispatch2 = $row['courier_price'];
$total2 = (($qty2*$pack_price2) + $dispatch2);
$total3 = $total2*1.2;
$output2 .= $total3;
$sum2 += $total3; // Add to overall total
$output2 .="\n";
}
Output:
http://i754.photobucket.com/albums/xx182/rache_R/Screenshot2014-07-03at113133_zpsbcc09900.png
Use this Code....
$output= "<table border='1' width='60%'><tr>";
$sql = " SELECT j.date ,
j.order_ref ,
j.quantity ,
j.packing_price ,
j.dispatch_type ,
j.courier_price
FROM Jobs j
WHERE j.order_type = 'Retail International'
AND j.confirmed = 'Yes' ";
$query = mysql_query($sql);
$total_columns = mysql_num_fields($query);
for ($i = 0; $i < $total_columns; $i++){
$heading = mysql_field_name($query, $i);
$output .= '<td>' . $heading . '</td>';
if(($i+1) == $total_columns) $output .= '<td>Total</td></tr>';
}
while ($row = mysql_fetch_array($query)) {
$total_price = 0;
$total_price =( ( $row['quantity'] * $row['packing_price'] ) +
$row['courier_price'] );
$total_price = $total_price * 1.2;
$timestamp = DateTime::createFromFormat('Y-m-d h:i:s',
$row['date'])->getTimestamp();
$output .= '<tr>';
$output .= '<td>' . date("d/m/Y", $timestamp) . '</td>';
$output .= '<tr>';
$output .= '<td>' . date("d/m/Y", strtotime($row['date']) . '</td>';
$output .= '<td>' . $row['order_ref'] . '</td>';
$output .= '<td>' . $row['quantity']. '</td>';
$output .= '<td>' . $row['packing_price'] . '</td>';
$output .= '<td>' . $row['dispatch_type'] . '</td>';
$output .= '<td>' . $row['courier_price'] . '</td>';
$output .= '<td>' . number_format($total_price, 2) . '</td>';
$output .= '</tr>';
}
$output .= "</table>";
echo '<br>' . $output;
I have a script which retrieves all rows of data within a sales list (npc_sales_list) but what I am trying to do is set up a drop down menu which filters the results oand I don't know where to start as I haven't done any php in while.
The main filters I am trying to do are to see the previous month's sales only (npc_entry_date) and the sales type (npc_usertype). If someone could point me in the right direction or show me some resource links that would be great.
Im not fussed whether the filter is automatic or if you need to hit a submit button. Any suggestions welcome...
<?php
require_once ('./includes/config.inc.php');
$page_title = 'Page title';
include ('./includes/header.html');
if (!isset($_SESSION['admin_sp_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1);
}
$url .= '/login.php';
ob_end_clean();
header("Location: $url");
exit();
}
require_once ('database.php');
$display = 500;
if (isset($_GET['np'])) {
$num_pages = $_GET['np'];
} else {
$query = "SELECT COUNT(*) FROM npc_sales_list ORDER BY npc_entry_date DESC";
$result = #mysql_query ($query);
$row = mysql_fetch_array ($result, MYSQL_NUM);
$num_records = $row[0];
if ($num_records > $display) {
$num_pages = ceil ($num_records/$display);
} else {
$num_pages = 1;
}
}
if (isset($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
$link1 = "{$_SERVER['PHP_SELF']}?sort=fna";
$link2 = "{$_SERVER['PHP_SELF']}?sort=lna";
if (isset($_GET['sort'])) {
switch ($_GET['sort']) {
case 'fna':
$order_by = 'sp_firstname ASC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=fnd";
break;
case 'fnd':
$order_by = 'sp_firstname DESC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=fna";
break;
case 'lna':
$order_by = 'sp_surname ASC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=lnd";
break;
case 'lnd':
$order_by = 'sp_surname DESC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=lna";
break;
default:
$order_by = 'npc_entry_date DESC';
break;
}
// $sort will be appended to the pagination links.
$sort = $_GET['sort'];
} else { // Use the default sorting order.
$order_by = 'npc_entry_date DESC';
$sort = 'drd';
}
$query = "SELECT us.sp_firstname , us.sp_surname , us.sp_amb_club_no , us.sp_position_title , us.sp_dealer_name ,
us.sp_dealer_code , us.sp_region , us.sp_department, sp_business_phone, us.sp_mobile_phone , us.sp_dealer_category, us.sp_email,
sa.npc_item_id , sa.npc_part_no, sa.npc_quantity, sa.npc_customer_name, sa.npc_registration_no , sa.npc_suo_no , sa.npc_amb_club_no , sa.npc_repair_order , sa.npc_invoice_no ,
sa.npc_entry_userdate, sa.npc_image_upload, sa.npc_usertype, sa.npc_points, sa.npc_bonus_points, sa.npc_active, sa.npc_entry_date,
DATE_FORMAT(sa.npc_entry_date, '%d-%m-%Y') AS dr , sa.sp_user_id
FROM sp_user AS us, npc_sales_list AS sa
WHERE us.sp_user_id = sa.sp_user_id
ORDER BY
$order_by LIMIT $start, $display";
$result = #mysql_query ($query);
//
// Table header.
echo '<table width="100%" cellspacing="1" cellpadding="4" style="font-size:10px;">
<tr>
<td align="center"><b>Invoice No.</b></td>
<td align="center"><b>Member ID</b></td>
<td align="center"><b>Surname</b></td>
<td align="center"><b>Part #</b></td>
<td align="center"><b>Sale Type</b></td>
<td align="center"><b>Qty</b></td>
<td align="center"><b>Invoice Date</b></td>
<td align="center"><b>Customer Rego</b></td>
<td align="center"><b>Submission Date</b></td>
<td align="center"><b>Status</b></td>
</tr>';
// Fetch and print all the records. echo '<td align="left"><strong>' . $row['sp_invoice_no'] . '</strong></td> ';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced');
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="center"><strong>Details</strong></td> ';
echo '<td align="center"><strong>' . $row['sp_amb_club_no'] . '</strong></td> ';
echo '<td align="center"><strong>' . $row['sp_surname'] . '</strong></td> ';
echo '<td align="center"> <strong>' . $row['npc_part_no'] . '<strong></td>';
echo '<td align="center"> ' . $row['npc_usertype'] . ' </td>';
echo '<td align="center"> ' . $row['npc_quantity'] . ' </td>';
echo '<td align="center"> ' . $row['npc_entry_userdate'] . ' </td>';
echo '<td align="center"> ' . $row['npc_registration_no'] . ' </td>';
echo '<td align="center"> ' . $row['dr'] . ' </td>';
echo '<td align="center" style="color:#5a8e22; font-weight:bold;"> ' . $row['npc_active'] . ' </td>';
echo '</tr>
';
}
echo '</table>';
mysql_free_result ($result);
mysql_close();
if ($num_pages > 1) {
echo '<br /><p>';
$current_page = ($start/$display) + 1;
if ($current_page != 1) {
echo '<a href="view-all-sales.php?s=' . ($start - $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Previous</a> ';
}
for ($i = 1; $i <= $num_pages; $i++) {
if ($i != $current_page) {
echo '<a href="view-all-sales.php?s=' . (($display * ($i - 1))) .
'&np=' . $num_pages . '&sort=' . $sort .'">' . $i . '</a> ';
} else {
echo $i . ' ';
}
}
if ($current_page != $num_pages) {
echo '<a href="view-all-sales.php?s=' . ($start + $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Next</a> ';
}
echo '</p>';
}
include ('./includes/footer_admin_user.html');
?>