how to make bill in php and sql - php

i have online shop and i have problem making the Bill for each order
let say someone buy 2 t-shart and 1 shoes it will add to the trolley table wich have prodcutid , usreid , Quantity , now if the user confirm the order how can i create bill with all the item he buy and save it to new database named bills
note that same user may have diffrent bill with different item
this is the code that display the orders and the total price
function CallMyOrder($identificador)
{
global $database_connectoos, $connectoos;
mysql_select_db($database_connectoos, $connectoos);
$query_CoryFuncion = sprintf("SELECT * FROM tbltrolley WHERE idUser = %s AND tbltrolley.intOrderDone = 1 , $identificador);
$CoryFuncion = mysql_query($query_CoryFuncion, $connectoos) or die(mysql_error());
$row_CoryFuncion = mysql_fetch_assoc($CoryFuncion);
$totalRows_CoryFuncion = mysql_num_rows($CoryFuncion);
?>
<?php
if ($totalRows_CoryFuncion > 0) { // Show if recordset not empty
echo " <li> User : ".CallUserName($row_CoryFuncion['idUser']);
$totalPrice =0;
$pricemultnumber;
do {
$pricemultnumber = $row_CoryFuncion['intQuantity'] * CallProductPrice($row_CoryFuncion['idProduct']);
echo "<li><br>";
echo "<img src='../document/product/".CallProductImage($row_CoryFuncion['idProduct'])."' border='0'/>";
echo "Product Name : ".CallProductName($row_CoryFuncion['idProduct']);
echo "<br>";
echo "Quantity : ".$row_CoryFuncion['intQuantity'];
echo "<br>";
echo "Price : ".$pricemultnumber." RM";
echo "<br></li>";
$totalPrice = $totalPrice + $pricemultnumber;
} while ($row_CoryFuncion = mysql_fetch_assoc($CoryFuncion));
echo "<br>";
echo "<p style='font-size: 24px; font-weight: bold;'>Tax : ".CallTax()."</p>";
$multp = (100 + CallTax())/100;
$totalPrice = $totalPrice * $multp;
echo "<p style='font-size: 24px; font-weight: bold;'>Total Price = ".$totalPrice." RM</p>";
}

Related

PHP Multidimensional Arrays + array_key_exists not working correctly

Before i start to explain in details, let me show the screenshot of what I want the result to be.
What I want to achieve is quite simple, display all the items that are added to cart and calculate the total for each individual product. However, looks like my Multidimensional Arrays and array_key_exists didn't do it correctly and that's why didn't get the result i want.
As you can see from the screenshot, if the same product being added to cart, the quantity didn't plus 1 and it just display below the previous item.
products.php -> nothing special, just to display all the products in database
<?php
require 'config.php';
$q = mysqli_query( $db->conn(), "SELECT * FROM product" );
if( mysqli_num_rows($q) > 0 ) { // Check if there are results
while( $row = mysqli_fetch_assoc($q)){
//echo "id: " . $row["id"]. " <br>- Name: " . $row["product_name"]. " " . $row["product_price"]. "";
echo '<p>ID->'.$row['id'].' | '.$row['product_name'].' | $'.$row['product_price'].'
| Add to Cart</p>';
}
}
?>
cart.php
<?php
session_start();
if(isset($_GET['id'])){
require 'config.php';
$id=$_GET['id'];
$q = mysqli_query( $db->conn(), "SELECT * FROM product where id='$id'" );
$row = mysqli_fetch_assoc($q);
$product_name=$row['product_name'];
$product_price=$row['product_price'];
$quantity=1;
$total=$quantity*$product_price;
if(!isset($_SESSION['cart'])){
$_SESSION['cart'][]=[]; //Create session 1st time
}
if(isset($_SESSION['cart'])){
if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}else {
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
}
echo '<table border="1" cellpadding="10">';
echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';
foreach ($_SESSION['cart'] as $key => $row) { // list out all the items in Multi array
echo "<tr>";
foreach ($row as $key2 => $val) {
echo "<th>";
echo $_SESSION['cart'][$key][$key2]." ";
echo "</th>";
}
echo "</tr>";
}
echo '</table>';
}
}
?>
May i know which part of the coding went wrong?
Revisiting the Code in your cart.php File would be of great Benefit here. Below is what you may want to consider:
<?php
$product_name = $row['product_name'];
$product_price = $row['product_price'];
$quantity = 1;
$total = $quantity*$product_price;
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
if(isset($_SESSION['cart'])){
// DOES THE PRODUCT ID EXIST IN THE $_SESSION['cart'] COLLECTION?
// IF IT DOESN'T WE CREATE IT AND LET IT BE...
if(!array_key_exists( $id, $_SESSION['cart'] )){
$_SESSION['cart'][$id] = [$id, $product_name, $product_price, $quantity, $total];
}else {
// IF IT ALREADY EXIST; WE SIMPLY GET THE OLD VALUES & APPEND NEW ONE TO IT...
// HERE YOU ASKED FOR array_key_exits($id, $_SESSION['cart']);
// WHICH MEANS $id MUST BE THE KEY HERE
// HERE IS WHERE THE PROBLEM IS....
$storedPrice = $_SESSION['cart'][$id][2];
$storedQuantity = $_SESSION['cart'][$id][3];
$storedTotal = $_SESSION['cart'][$id][4];
$_SESSION['cart'][$id] = [
$id,
$product_name,
$product_price,
$storedQuantity+1,
round( ($storedQuantity+1)*($product_price), 2),
];
}
echo '<table border="1" cellpadding="10">';
echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';
foreach ($_SESSION['cart'] as $key => $row) {
echo "<tr>";
foreach ($row as $key2 => $val) {
echo "<th>";
echo $_SESSION['cart'][$key][$key2]." ";
echo "</th>";
}
echo "</tr>";
}
echo '</table>';
}
You have made the mistake, when add a Cart and Update Cart:
So change the following line:
if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}else {
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
}
Into
$find = false;
if(!empty($_SESSION['cart'])){
foreach($_SESSION['cart'] as $key=>$cart){
if(isset($cart[0]) && $cart[0] == $id){ //Already exists in Cart
$_SESSION['cart'][$key][3] = $_SESSION['cart'][$key][3] + 1; //$_SESSION['cart'][$key][3] is quantity
$_SESSION['cart'][$key][4] = $_SESSION['cart'][$key][3] * $_SESSION['cart'][$key][2] ; //$_SESSION['cart'][$key][4] update the total
$find = true;
}
}
}
if(!$find){ //Not in the Cart
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}
Note: Before check, clear the cookies

Checking all $_POST values for answer and printing

I am creating an online grocery site where a user can enter his/her full name & address and then proceed to purchase groceries.
There are 20 grocery items to choose from - if the user wants an item, they can simply enter how many units of that item they want; this is the html code for for just 1 of the 20 items.
<tr>
<td> Milk - $3.99/carton </td>
<td> <input type="number" name="amtMilk" min=0> </td>
</tr>
At the bottom of the page there is a submit button which leads to a confirmation page in php. The confirmation page outputs the users name, address, all the items ordered and a total before and after tax.
I have written out the PHP for this however, it doesn't seem to be working correctly. Below is my code shortened to 4 items:
<?php
<h2> Customer Details: </h2>
<p>Customer Name: </p> echo $_POST['Name'];
<p>Address: </p> echo $_POST['Address'];
$total = 0;
<p>You ordered: </p>
$POSTvalues = array('amtMilk', 'amtEggs', 'amtBread', 'amtCereal');
foreach($POSTvalues as $key) {
if ($_POST['amtMilk'] > 0) {
$total+= 3.99*($_POST['amtMilk']);
echo "Milk";
}
elseif ($_POST['amtEggs'] > 0 ) {
$total+= 2.99*($_POST['amtEggs']);
echo "Eggs";
}
elseif ($_POST['amtBread'] > 0 ) {
$total+= 1.50*($_POST['amtBread']);
echo "Bread";
}
elseif ($_POST['amtCereal'] > 0 ) {
$total+= 4.99*($_POST['amtCereal']);
echo "Cereal";
}
}
echo "Your total before Tax is: $total"; <br>
$afterTax = $total*0.13 + $total
$afterDelivery = $afterTax + 3.50
echo "Your total after tax is: $afterTax"; <br>
echo "Your total after delivery is: $afterDelivery";<br>
<h3> GRAND TOTAL: </h3> echo "$afterDelivery";
?>
Can anyone point out what i'm doing wrong or how I can fix this so get the desired output?
There is no need for the foreach loop, and thus no need for the $POSTvalues array.
Use independent if statements without the elseif.
A little psuedocode...
if (value1 > 0 )
{
add to total
print item
}
if (value2 > 0 )
{
add to total
print item
}
if (value3 > 0 )
{
add to total
print item
}
if (value4 > 0 )
{
add to total
print item
}
Fun fact: PHP turns elements with names structured like arrays into PHP arrays.
So, you can do this:
<?php
$array = array(
"milk" => array(
"price" => 3.99,
"unit" => "carton",
),
"eggs" => array(
"price" => 2.99,
"unit" => "dozen",
),
);
if (isset($_POST['amt'])) {
var_dump($_POST['amt']);
$total = 0;
foreach ($_POST['amt'] as $name=>$num) {
if($num > 0) {
$price = $array[$name]['price'];
$amt = $_POST['amt'];
$total += $price * $num;
echo $num . " " . ucfirst($name) . ", ";
}
}
echo "<br />Your total before Tax is: $total<br />";
$afterTax = $total*0.13 + $total;
$afterDelivery = $afterTax + 3.50;
echo "Your total after tax is: $afterTax<br />";
echo "Your total after delivery is: $afterDelivery<br />";
echo '<form method="POST"><button type="submit">Back</button></form>';
} else {
?><form method="POST"><table><?php
foreach ($array as $name=>$item) {
?>
<tr>
<td> <?php echo ucfirst($name); ?> - $<?php echo $item['price']; ?>/<?php echo $item['unit']; ?> </td>
<td> <input type="number" name="amt[<?php echo $name; ?>]" min=0> </td>
</tr><?php
}
?></table><input type="submit"></form><?php
}
I would consider either passing your price as a hidden field (for example, with the name price[milk]), or ensuring your array is available after you've submitted the form like I have done above. That way you don't have to hard-code in prices. The way you have it, it's going to be a nightmare to change if the prices change!
To add a new item, all you need to do is add a new key/array pair to the $array. No additional coding on the back-end. Just results.
Check it out here.
you're doing many things wrong.
so, how are you trying to display html inside php without using print/echo?
So here's revised code, hope this will resolve your issues.
<?php
echo '<h2> Customer Details: </h2>';
echo '<p>Customer Name: </p>'. $_POST['Name'];
echo '<p>Address: </p>'. $_POST['Address'];
$total = 0;
echo '<p>You ordered: </p>';
$POSTvalues = array('amtMilk', 'amtEggs', 'amtBread', 'amtCereal');
//foreach($POSTvalues as $key)
{
if (isset($_POST['amtMilk']) && $_POST['amtMilk'] > 0) {
$total+= 3.99*($_POST['amtMilk']);
echo "Milk";
}
if (isset($_POST['amtEggs']) && $_POST['amtEggs'] > 0) {
$total+= 2.99*($_POST['amtEggs']);
echo "Eggs";
}
if (isset($_POST['amtBread']) && $_POST['amtBread'] > 0) {
$total+= 1.50*($_POST['amtBread']);
echo "Bread";
}
if (isset($_POST['amtCereal']) && $_POST['amtCereal'] > 0 ) {
$total+= 4.99*($_POST['amtCereal']);
echo "Cereal";
}
}
echo "Your total before Tax is: $total<br />";
$afterTax = $total*0.13 + $total;
$afterDelivery = $afterTax + 3.50;
echo "Your total after tax is: $afterTax<br />";
echo "Your total after delivery is: $afterDelivery<br />";
echo "<h3> GRAND TOTAL: </h3>$afterDelivery";
?>
EDIT
Comment out the foreach($POSTvalues as $key) and change all elseif to if.
add another condition in if statement like this && $_POST['amtCereal'] > 0 to ensure that it has value greater than 0

Magento review for logged in customer on one product

I have a loop that shows all products that a customer has ordered, within that loop I want to pull out if the customer has rated that one product what rating they have given it. I think the problem is I need to use review/summary to display the rating?
$productsreviews = Mage::getModel('review/review')->getProductCollection()->addCustomerFilter(Mage::getSingleton('customer/session')->getCustomerId())->setDateOrder();
foreach ($productsreviews as $productsreview)
{
$product = Mage::getModel('catalog/product')->load($productsreview->getData('entity_pk_value'));
}
echo $product->getRating();
EDIT:Full Code
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
/* Get the customer data */
$customer = Mage::getSingleton('customer/session')->getCustomer();
/* Get the customer's email address */
$customer_email = $customer->getEmail();
$customer_id = $customer->getId();
}
$collection = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_email', array(
'like' => $customer_email
));
$uniuqProductSkus = array();
foreach ($collection as $order) {
$order_id = $order->getId();
$order = Mage::getModel("sales/order")->load($order_id);
$ordered_items = $order->getAllItems();
foreach ($ordered_items as $item)
{
if (in_array($item->getProduct()->getSku(), $uniuqProductSkus)) {
continue;
} else {
array_push($uniuqProductSkus, $item->getProduct()->getSku());
$_product = Mage::getModel('catalog/product')->load($item->getProductId());
$product_small_image_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(200);
$product_thumbnail_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(150);
$summaryData = Mage::getModel('review/review_summary')->load($item->getProductId());
echo "<li>";
echo "<div class='previous-name'><p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "'>";
echo $item->getName() . "</a></p></div>";
echo "<div class='previous-image'><a href='" . $_product->getProductUrl() . "'>";
echo "<img src='" . $product_small_image_path . "' />";
echo "</a></div>";
echo "<div class='previous-rating'>";
echo "<p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "#product_tabs_review_tabbed'>Review this beer now</a></p>";
echo $summaryData->getRatingSummary() . '% Would buy again <br/>';
echo "<div class='rating-box' style='float:left;'>";
echo "<div class='rating' style='width:" . $summaryData->getRatingSummary() . "%'></div></div>";
echo "<div class='previous-clear'></div></div>";
?>
review/summary will display the aggregated data. IIRC there's no method to pull out single review along with rating using the review model. This should give you the review object with associated rating:
$cReviews = Mage::getModel('review/review')->getResourceCollection()
->addStoreFilter($oProduct->getStoreId())
->addRateVotes()
->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
->addEntityFilter('product', $oProduct->getId())
->setDateOrder()
->addFieldToFilter('customer_id', $yourCustomerId);
$cReviews->getSelect()->limit(1);
$oReview = $cReviews->getFirstItem();
Then you will have to calculate rating average for the single review:
if ( ($cRatings = $oReview->getRatingVotes()) && count($cRatings) ) {
$rAverage = array_sum($cRatings->getColumnValues('value')) / count($cRatings);
}

How to display information in another PHP Page

I am having trouble with a mini shopping cart. I have created the mini shopping cart and when a product is added it goes into the Basket page. However, i want to create a checkout page. How do i grab the products in the basket and put it in a checkout page.
So For example, the check out page will look like this
ITEM NAME, ITEM MODEL, ITEM PRICE
TOTAL OF ITEMS
CHECKOUT BUTTON (links to a payment system)
This is my Basket.php code:
<?php
$bikecode = $_GET['id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
if($bikecode && !productExists($bikecode)) {
die("Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$bikecode]++; //add one to the quantity of the product with id $bikecode
break;
case "remove":
$_SESSION['cart'][$bikecode]--; //remove one from the quantity of the product with id $bikecode
if($_SESSION['cart'][$bikecode] == 0) unset($_SESSION['cart'][$bikecode]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
if($_SESSION['cart']){
echo "<table width=\"100%\">";
foreach($_SESSION['cart'] as $bikecode => $quantity) {
$sql = sprintf("SELECT BikeCode, Model, Price FROM Bike WHERE BikeCode = '%s';", $bikecode);
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0) {
list($bikecode, $model, $price) = mysqli_fetch_row($result);
$cost = $quantity * $price;
$total = $total + $cost;
echo "<tr><th>BikeCode:</th><th>Model:</th><th>Quantity:</th><th>Price:</th></tr>";
echo "<tr>";
echo "<td align=\"center\">$bikecode</td>";
echo "<td align=\"center\">$model</td>";
echo "<td align=\"center\">$quantity X</td>";
echo "<td align=\"center\">£$cost</td>";
echo "</tr>";
}
}
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\">Total</td>";
echo "<td align=\"right\">£$total</td>";
echo "</tr>";
echo "<tr>";
echo "<td colspan=\"4\" align=\"right\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
}else{
echo "You have no items in your shopping cart.";
}
function productExists($bikecode) {
$sql = sprintf("SELECT * FROM Bike WHERE BikeCode = '%s';", $bikecode);
return mysqli_num_rows(mysqli_query($con, $sql)) > 0;
}
?>
As long as you have a session_start(); on top of every page you should be able to use the exact same foreach loop as you do in this piece of coding. The session with the information would just be carried over to the next page.
Assume you have a page called test.php with the following code:
<?php
session_start();
$_SESSION['test'] = 1;
echo $_SESSION['test'];
?>
Then to access the test variable in othertest.php page,simply do the following:
<?php
session_start();
echo $_SESSION['test']; ?>
You forgot to add session_start() to the top of your php file. I recommend adding session_start() to a separate file and then including that file in each of the php pages that uses session variables.

How can I populate HTML table numbered rows based on whether they match row number?

So, I asked this question earlier this week, and #newfurniturey helped me out, but now I have a new problem: I'd like to be able to put devices in that span more than one U (hence, the usize column in the devices db table) - some devices can span take up half a cabinet. Also, I'd like to be able to mark devices as being in the front or rear of the cabinet, but that should be simple enough for me to figure out.
Here's the working code (see old question for db setup) for just 1U devices:
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
<!--
function clickHandler(e)
{
var targetId, srcElement, targetElement;
if (window.event) e = window.event;
srcElement = e.srcElement? e.srcElement: e.target;
if (srcElement.className == "Outline")
{
targetId = srcElement.id + "d";
targetElement = document.getElementById(targetId);
if (targetElement.style.display == "none")
{
targetElement.style.display = "";
srcElement.src = "images/minus.gif";
}
else
{
targetElement.style.display = "none";
srcElement.src = "images/plus.gif";
}
}
}
document.onclick = clickHandler;
-->
</SCRIPT>
<noscript>You need Javascript enabled for this page to work correctly</noscript>
<?
function sql_conn()
{
$username="root";
$password="root";
$database="racks";
$server="localhost";
#mysql_connect($server,$username,$password) or die("<h2 align=\"center\" class=\"red\">[<img src=\"images/critical.gif\" border=\"0\">] Unable to connect to $server [<img src=\"images/critical.gif\" border=\"0\">]</h2>");
#mysql_select_db($database) or die("<h2 align=\"center\" class=\"red\">[<img src=\"images/critical.gif\" border=\"0\">] Unable to select $database as a database [<img src=\"images/critical.gif\" border=\"0\">]</h2>");
}
sql_conn();
$sql_datacenters="SELECT * FROM `datacenters`";
$result_datacenters=mysql_query($sql_datacenters);
$j=0;
echo "<table border='1' style='float:left;'>";
while ($datacenters_sqlrow=mysql_fetch_array($result_datacenters))
{
echo "<tr><td>";
echo "<h2 class='black' align='left'>";
echo "<IMG SRC='images/plus.gif' ID='Out" . $j . "' CLASS='Outline' STYLE='cursor:hand;cursor:pointer'>"; // fancy icon for expanding-collapsing section
echo " " . $datacenters_sqlrow['rack'] . ": " . $datacenters_sqlrow['cagenum'] . "</h2>"; // datacenter name and cage number
echo "<div id=\"Out" . $j . "d\" style=\"display:none\">"; // opening of div box for section that is to be expanded-collapsed
echo $datacenters_sqlrow['notes'] . "<br /><br />"; // datacenter notes
$sql_cabinets="SELECT * FROM `cabinets` WHERE `datacenter` = '$datacenters_sqlrow[0]' ORDER BY `cabinetnumber` ASC";
$result_cabinets=mysql_query($sql_cabinets);
while ($cabinets_sqlrow=mysql_fetch_array($result_cabinets))
{
$sql_devices="SELECT * FROM `devices` WHERE `datacenter` = '$datacenters_sqlrow[0]' AND `cabinet` = '$cabinets_sqlrow[1]' ORDER BY `ustartlocation` ASC";
$result_devices=mysql_query($sql_devices);
echo "<table border='1' style='float:left;'>"; // opening of table for all cabinets in datacenter
echo "<tr><td colspan='2' align='middle'>" . $cabinets_sqlrow[1] . "</td></tr>"; // cabinet number, spans U column and device name column
$devices = array();
while($row = mysql_fetch_array($result_devices)) {
$devices[$row['ustartlocation']] = $row['devicename'];
}
for ($i = 0; $i < $cabinets_sqlrow[2]; $i++) // iterates through number of U in cabinet
{
$u = $cabinets_sqlrow[2] - $i; // subtracts current $i value from number of U in cabinet since cabinets start their numbers from the bottom up
echo "<tr>";
echo "<td width='15px' align='right'>$u</td>"; // U number
echo (isset($devices[$u]) ? "<td width='150px' align='middle'>$devices[$u]</td>" : "<td width='150px' align='middle'>empty</td>");
echo "</tr>";
}
echo "</table>"; // closes table opened earlier
}
echo "</td></tr>";
echo "</div>"; // close for div box that needs expanding-collapsing by fancy java
$j++; // iteration for the fancy java expand-collapse
}
echo "</table>";
mysql_close();
?>
Based on your previous question, each ustartlocation is unique (hence why you can use it as an index in your $devices array). Using this same concept, you could populate the $devices array from "ustartlocation to (ustartlocation + (usize - 1))".
$devices = array();
while($row = mysql_fetch_array($result_devices)) {
$endLocation = ($row['ustartlocation'] + ($row['usize'] - 1));
for ($location = $row['ustartlocation']; $location <= $endLocation; $location++) {
$devices[$location] = $row['devicename'];
}
}
Because your display-loop already iterates through each U and displays the device assigned, you shouldn't need to modify any other portion. However, the caveat to this is that the device-name will repeat for every U instead of span it. To span it, we'll need to do a little more work.
To start, we could just store the usize in the $devices array instead of filling in each individual position. Also, to prevent a lot of extra work/calculations later, we'll also store a "placeholder" device for each additional position.
while($row = mysql_fetch_array($result_devices)) {
// get the "top" location for the current device
$topLocation = ($row['ustartlocation'] + $row['usize'] - 1);
// populate the real position
$devices[$topLocation] = $row;
// generate a list of "placeholder" positions
for ($location = ($topLocation - 1); $location >= $row['ustartlocation']; $location--) {
$devices[$location] = 'placeholder';
}
}
Next, in your display-loop, you will check if the current position is a placeholder or not (if so, just display the U and do nothing for the device; if it isn't, display the device, or 'empty'). To achieve the "span" effect for each device, we'll set the cell's rowspan equal to the device's usize. If it's 1, it will be a single cell; 2, it will span 2 rows, etc (this is why "doing nothing" for the device on the placeholder-rows will work):
for ($i = 0; $i < $cabinets_sqlrow[2]; $i++) {
$u = $cabinets_sqlrow[2] - $i;
echo "<tr>";
echo '<td width="15px" align="right">' . $u . '</td>';
if (isset($devices[$u])) {
// we have a "device" here; if it's a "placeholder", do nothing!
if ($devices[$u] != 'placeholder') {
echo '<td width="150px" align="middle" rowspan="' . $devices[$u]['usize'] . '">' . $devices[$u]['devicename'] . '</td>';
}
} else {
echo '<td width="150px" align="middle">empty</td>';
}
echo "</tr>";
}
So, as it can be seen - the first method above that simply repeats the device for each U it spans is much simpler. However, the second method will present a more user-friendly display. It's your preference to which method you want to use and which one you think will be more maintainable in the future.
UPDATE (code-fix & multi-direction spanning)
I didn't realize that your table was being built in descending-order so I had the ustartlocation as the "top location" which caused an erroneous row/cell shift. I've fixed the code above to properly set a "top location" based on the ustartlocation and usize for each device that will fix that issue.
Alternatively, as direction may or may not be important, I've customized the $devices-populating loop (below) to support creating a row-span that goes either upwards or downwards, completely depending on the flag you specify. The only code you'll need to change (if you already have the customized display-loop from above) would be the while loop that populates $devices:
$spanDevicesUpwards = true;
while($row = mysql_fetch_array($result_devices)) {
if ($row['usize'] == 1) {
$devices[$row['ustartlocation']] = $row;
} else {
$topLocation = ($spanDevicesUpwards ? ($row['ustartlocation'] + $row['usize'] - 1) : $row['ustartlocation']);
$bottomLocation = ($spanDevicesUpwards ? $row['ustartlocation'] : ($row['ustartlocation'] - $row['usize'] + 1));
$devices[$topLocation] = $row;
for ($location = ($topLocation - 1); $location >= $bottomLocation; $location--) {
$devices[$location] = 'placeholder';
}
}
}
This new block of code will, if the usize spans more than 1, determine the "top cell" and "bottom cell" for the current device. If you're spanning upwards, the top-cell is ustartlocation + usize - 1; if you're spanning downwards, it's simply ustartlocation. The bottom-location is also determined in this manner.
Hoping this will work for you..........for front/rear you can name you device as SERVER3/front or SERVER3/rear:
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
<!--
function clickHandler(e)
{
var targetId, srcElement, targetElement;
if (window.event) e = window.event;
srcElement = e.srcElement? e.srcElement: e.target;
if (srcElement.className == "Outline")
{
targetId = srcElement.id + "d";
targetElement = document.getElementById(targetId);
if (targetElement.style.display == "none")
{
targetElement.style.display = "";
srcElement.src = "images/minus.gif";
}
else
{
targetElement.style.display = "none";
srcElement.src = "images/plus.gif";
}
}
}
document.onclick = clickHandler;
-->
</SCRIPT>
<noscript>You need Javascript enabled for this page to work correctly</noscript>
<?
function sql_conn()
{
$username="root";
$password="root";
$database="racks";
$server="localhost";
#mysql_connect($server,$username,$password) or die("<h2 align=\"center\" class=\"red\">[<img src=\"images/critical.gif\" border=\"0\">] Unable to connect to $server [<img src=\"images/critical.gif\" border=\"0\">]</h2>");
#mysql_select_db($database) or die("<h2 align=\"center\" class=\"red\">[<img src=\"images/critical.gif\" border=\"0\">] Unable to select $database as a database [<img src=\"images/critical.gif\" border=\"0\">]</h2>");
}
sql_conn();
$sql_datacenters="SELECT * FROM `datacenters`";
$result_datacenters=mysql_query($sql_datacenters);
$j=0;
echo "<table border='1' style='float:left;'>";
while ($datacenters_sqlrow=mysql_fetch_array($result_datacenters))
{
echo "<tr><td>";
echo "<h2 class='black' align='left'>";
echo "<IMG SRC='images/plus.gif' ID='Out" . $j . "' CLASS='Outline' STYLE='cursor:hand;cursor:pointer'>"; // fancy icon for expanding-collapsing section
echo " " . $datacenters_sqlrow['rack'] . ": " . $datacenters_sqlrow['cagenum'] . "</h2>"; // datacenter name and cage number
echo "<div id=\"Out" . $j . "d\" style=\"display:none\">"; // opening of div box for section that is to be expanded-collapsed
echo $datacenters_sqlrow['notes'] . "<br /><br />"; // datacenter notes
$sql_cabinets="SELECT * FROM `cabinets` WHERE `datacenter` = '$datacenters_sqlrow[0]' ORDER BY `cabinetnumber` ASC";
$result_cabinets=mysql_query($sql_cabinets);
while ($cabinets_sqlrow=mysql_fetch_array($result_cabinets))
{
$sql_devices="SELECT * FROM `devices` WHERE `datacenter` = '$datacenters_sqlrow[0]' AND `cabinet` = '$cabinets_sqlrow[1]' ORDER BY `ustartlocation` ASC";
$result_devices=mysql_query($sql_devices);
echo "<table border='1' style='float:left;'>"; // opening of table for all cabinets in datacenter
echo "<tr><td colspan='2' align='middle'>" . $cabinets_sqlrow[1] . "</td></tr>"; // cabinet number, spans U column and device name column
$devices = array();
$devices_size=array();
while($row = mysql_fetch_array($result_devices)) {
$devices[$row['ustartlocation']] = $row['devicename'];
//$devices_size[$row['ustartlocation']+$row['usize']-1] = $row['usize'];
$devices_size[$row['ustartlocation']] = $row['usize'];
}
$start="";
$new="";
for ($i = 0; $i < $cabinets_sqlrow[2]; $i++) // iterates through number of U in cabinet
{
$u = $cabinets_sqlrow[2] - $i; // subtracts current $i value from number of U in cabinet since cabinets start their numbers from the bottom up
echo "<tr>";
echo "<td width='15px' align='right'>$u</td>"; // U number
$rowspan=$devices_size[$u];
//$rowspan1=$
if($rowspan>1)
{
$start=$u;
$new=$u-$rowspan+1;
echo (isset($devices[$u]) ? "<td width='150px' align='middle' rowspan='".$rowspan."'>$devices[$u]</td>" : "<td width='150px' align='middle' rowspan='".$rowspan."'>$devices[$new]</td>");
}
else{
if($u<=$start && $u>=$new)
{
}
else
{
echo (isset($devices[$u]) ? "<td width='150px' align='middle' >$devices[$u]</td>" : "<td width='150px' align='middle'>empty".$row."".$u."</td>");
}
}
echo "</tr>";
}
echo "</table>"; // closes table opened earlier
}
echo "</td></tr>";
echo "</div>"; // close for div box that needs expanding-collapsing by fancy java
$j++; // iteration for the fancy java expand-collapse
}
echo "</table>";
mysql_close();
?>

Categories