$banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
$total_price2=$rows3['qty']*$rows3['number'];
$banana = $banana + 1;
if ($total_price2!=0)
{
if ($banana %2 ==0)
{
echo "<tr class=\"alt\">";
}
else
{
echo "<tr>";
}
echo "<td>".$rows3['member']."</td>";
echo "<td>".$rows3['payment']."</td>";
echo "<td>$".number_format($total_price2,2)."</td>";
}
echo "</tr>";
}
Problems:
The "banana" alternates the colour of the table row (class="alt") by using modulus (%) to check if banana is a odd number.
Not Working, I see the browser is self-closing the opening <tr> tag.
eg:
<tr><td>person</td><td>data</td><td>$10.00</td></tr>
<tr class="alt"></tr> (Repeats in this fashion)
UPDATE
I have discovered that the reiterating banana always returns ODD NUMBERS: 1 , 3, 5, etc
MySQL is not running correctly
SELECT table1.member, table1.paid, table1.payment,table2.qty,table3.number FROM table1,table2,table3 WHERE table1.member = table2.member AND table1.payment="fruit"
It is giving me wrong data like so:
person1 $10.00
person1 $0.00
person2 $10.00
person2 $0.00
etc
If all else fails, you could just use CSS:
tr {background-color: blue;}
tr:nth-of-type(2n) {background-color: red;}
Try doing this for a debug first:
echo "<tr class=\"alt\"> ";
My guess is that you have no data contained in your <tr> and is being squished to 0 px tall by your browser.
EDIT: I'm not entirely sure giving a class to your <tr> will filter down into the <td> based on certain browser DOM parsing. Whenever I do a zebra row, I'll assign the class to the <td>. I'm no designer by any standard, though. :)
Humor me and try this please:
$banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
$total_price2=$rows3['qty']*$rows3['number'];
$banana++;
if ($banana % 2 == 0) {
$td_class = "alt";
} else {
$td_class = "";
}
echo "<tr>";
if ($total_price2!=0) {
echo "<td class='{$td_class}'>".$rows3['member']."</td>";
echo "<td class='{$td_class}'>".$rows3['payment']."</td>";
echo "<td class='{$td_class}'>$".number_format($total_price2,2)."</td>";
}
echo "</tr>";
}
That's not going to work. You're only opening the table row if $total_price2!=0. It seems you should only output the closing </tr> tag inside that IF block.
Try this instead:
<?php
$banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
$total_price2=$rows3['qty']*$rows3['number'];
if ( !$total_price2)
continue;
$banana = $banana + 1;
if ($banana %2 ==0)
{
echo "<tr class=\"alt\">";
}
else
{
echo "<tr>";
}
echo "<td>".$rows3['member']."</td>";
echo "<td>".$rows3['payment']."</td>";
echo "<td>$".number_format($total_price2,2)."</td>";
echo "</tr>";
}
Related
I have a website and I prediction soccer. http://goaltips.nl/zeynel/Almanya2.php
I want to change background color(green) of the away wins fields if the nummer is bigger than 40 and Data is bigger than 5.
I have use this code for main page;
<?php
include 'almanya2fft.php';
include 'almanya2macsonu.php';
include 'almanya2ikibucuk.php';
foreach($array as $key => $data) {
echo "<tr>";
echo "<td>".$data['H']."</td>";
echo "<td>".$data['M']."</td>";
echo "<td>".$AwayPrediction[$key]."</td>";
echo "<td>".$IkiBucukAltPrediction[$key]." \r %".$IkiBucukUstPrediction[$key]."</td>";
echo "<td>".$VerisayisiData[$key]."</td>";
}
?>
</table>
</div>
and for almanya2ikibucuk.php is;
foreach($array as $key => $val) {
$IkiBucukAlt=0;
$IkiBucukUst=0;
$Verisayisi=0;
$sql = "SELECT * FROM Almanya2 where B = '{$val['B']}' AND E = '{$val['E']}' AND F = '{$val['F']}' AND O ='{$val['O']}' AND A = '*' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rowcount=mysqli_num_rows($result);
// output data of each row
while($row = $result->fetch_assoc()) {
if($row['T'] == A){
$IkiBucukAlt++;
}else{
$IkiBucukUst++;
}
}
//We use an array rather than overriding everytime
$VerisayisiData[$key]=$rowcount;
$IkiBucukAltPrediction[$key] = round(($IkiBucukAlt/$rowcount )*100);
$IkiBucukUstPrediction[$key] = round(($IkiBucukUst/$rowcount)*100);
} else {
echo " ";
}
}
$conn->close();
?>
What is the best way to do this conditions.
I hoop i was clear and someone can help me...
Thank you.
Right after you started your foreach loop get the needed color :
$color = '';
if ($AwayPrediction[$key] > 40 && $VerisayisiData[$key] > 5) {
$color = "style='background-color : green';";
}
Then add the style to each cell :
echo "<td ".$color.">".$AwayPrediction[$key]."</td>";
So when the condition is true, an inline css is applied and colors your cell else it does nothing.
You can do it with ternary operator:
foreach($array as $key => $data) {
$color = $AwayPrediction[$key] > 40 && $VerisayisiData[$key] > 5 ? 'style="background-color:green"' : '';
echo "<tr $color>";
echo "<td>".$data['H']."</td>";
echo "<td>".$data['M']."</td>";
echo "<td>".$AwayPrediction[$key]."</td>";
echo "<td>".$IkiBucukAltPrediction[$key]." \r %".$IkiBucukUstPrediction[$key]."</td>";
echo "<td>".$VerisayisiData[$key]."</td>";
}
I've been around for years on Stack but this is my first time posting. I'm working on a website (php + mysql) and the following problem is driving me absolutely nuts.
I have a table with 2 columns: Size and Amount. The table is generated by a basic php script simply outputting values stored in the database as rows in the table. Super basic, no fancy stuff there:
SELECT Size, Amount FROM database WHERE product = 'product123' ORDER BY Size ASC
The php echo outputs an html table displaying Size and the corresponding available packs (Amount).
Echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>'
Some Sizes are available in different Amounts, so therefore a particular Size can appear multiple times. Example:
Size | Amount
1 | 10
1 | 50
2 | 10
2+ | 10
3 | 40
3+ | 25
3+ | 40
4+ | 25
What I'm looking to achieve is that rows containing the same Size have the same background color. So it should alternate, grouped by Size, and this is irregular unfortunately. Example:
Size | Amount
1 | 10 < yellow
1 | 50 < yellow
2 | 10 < transparent
2+ | 10 < yellow
3 | 40 < transparent
3+ | 25 < yellow
3+ | 40 < yellow
4+ | 25 < transparent
So if the next Size is different from the preceding one, the row background color should change. This way a single Size is alternately highlighted as a group. Note that Size 2 and 2+ (same for 3 and 3+) are considered to be different sizes, hence the background color should change.
I can't figure out how to achieve this with php. The difficulty is that I can't use an evaluation based on odd/even since there sometimes is a "+" involved, making not all Sizes numeric values. Changing the naming scheme to get rid of that "+" is not an option unfortunately.
I was thinking of somehow having php check, while generating the table row by row, if the next outputted Size is identical to the preceding one. If yes: no change in bg-color. If no: change bg-color. However I can't figure out what the best way is to code something like this. Any pointers in the right direction are much appreciated.
Just a MCVE:
// your data
$records[] = array('size' => "1");
$records[] = array('size' => "1");
$records[] = array('size' => "2");
$records[] = array('size' => "2+");
$records[] = array('size' => "3");
$records[] = array('size' => "3+");
$records[] = array('size' => "3+");
$records[] = array('size' => "4");
$lastSize = $records[0]['size'];
$color = "yellow";
foreach ($records as $record) {
if ($lastSize != $record['size']) {
$lastSize = $record['size'];
if ($color == "yellow") $color = "transparent";
else $color = "yellow";
}
$lastSize == $record['size'];
echo $record['size'].' - '.$color.'<br>';
}
// OUTPUT:
// 1 - yellow
// 1 - yellow
// 2 - transparent
// 2+ - yellow
// 3 - transparent
// 3+ - yellow
// 3+ - yellow
// 4 - transparent
Ok, we'll start at the end. You probably want to put your color on the <tr>. The cleanest way to do it would be using css classes.
if ($newSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
We'll figure out how to get the right value into $newSize in a moment. Next, we need the css for classes above, so make sure this is in your styles somewhere:
.transparentRow {
background-color: transparent;
}
.yellowRow {
background-color: yellow;
}
Ok, lets rip the + off the size:
$plainSize = trim($record['size'], '+')
Ok, we use that for comparison, using an ever changing $oldSize valiable. Here is a full, functional, block:
$oldSize = 0;
foreach($whatever as $record) {
$plainSize = trim($record['size'], '+')
if ($plainSize == $oldSize) {
$newSize = false;
} else {
$newSize = true;
}
$oldSize = $plainSize;
if ($newSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>';
echo '</td>';
}
Some cleanup can lead to this:
$oldSize = 0;
foreach($whatever as $record) {
$plainSize = trim($record['size'], '+')
if ($plainSize == $oldSize) {
echo '<tr class="tranparentRow">';
} else {
echo '<tr class="yellowRow">';
}
$oldSize = $plainSize;
echo '<td>'.$record['size'].'</td><td>'.$record['amount'].'</td>';
echo '</td>';
}
I hope that helped not just with this problem, but with an example of how you can approach many other problems. Start at the end, work your way back.
As my comment suggested, use a double foreach() + implode() (and yet another solution):
<?php
$array[] = array("size"=>1,"amount"=>50);
$array[] = array("size"=>2,"amount"=>10);
$array[] = array("size"=>"2+","amount"=>10);
$array[] = array("size"=>3,"amount"=>40);
$array[] = array("size"=>"3+","amount"=>25);
$array[] = array("size"=>"3+","amount"=>40);
$array[] = array("size"=>"3+","amount"=>25);
$array[] = array("size"=>'4+',"amount"=>30);
// Sort by size
foreach($array as $row) {
$new[$row['size']][] = $row['amount'];
}
?>
<table>
<?php
$i = 0;
// Loop through the sorted groups
foreach($new as $size => $amts) {
// Determine odd or even
$color = ($i % 2 == 0)? "yellow":"transparent";
?> <tr>
<td class="<?php echo $color; ?>"><?php echo $size; ?></td>
<td class="<?php echo $color; ?>"><?php echo implode("</td>".PHP_EOL."</tr>".PHP_EOL."<tr>".PHP_EOL.'<td class="'.$color.'">'.$size.'</td><td class="'.$color.'">',$amts); ?></td>
</tr>
<?php $i++;
}
?>
</table>
You can do this using php sessions like this
session_start();
$_SESSION["pre_val"]='not set';
$_SESSION["pre_class"]='transparent';
//in your loop for showing table
//your loop starts
if($_SESSION["pre_val"]==$record['size']){
$suitable_class=$_SESSION["pre_class"];
}
else{
if($_SESSION["pre_class"]=='yellow'){$suitable_class='transparent';}
else{$suitable_class='yellow';}
}
//setting current values to session
$_SESSION["pre_class"] = $suitable_class;
$_SESSION["pre_val"] = $record['size'];
Echo '<tr class="$suitable_class"><td>'.$record['size'].'</td><td>'.$record['amount'].'</td></tr>';
//your loop ends
in your css
.yellow{background-color:yellow;}
.transparent{ background-color: rgba(255, 0, 0, 0.5);}
hope this solve your problem
Some for loop fun while printing out the table
$rows = array(
array("size"=>"1" ,"amount"=>"10"),
array("size"=>"1" ,"amount"=>"50"),
array("size"=>"2" ,"amount"=>"10"),
array("size"=>"2+","amount"=>"10"),
array("size"=>"3" ,"amount"=>"40"),
array("size"=>"3+","amount"=>"25"),
array("size"=>"3+","amount"=>"40"),
array("size"=>"4+","amount"=>"25")
);
echo "
<table>
<thead>
<tr><th>Size</th><th>Amount</th></tr>
</thead>
<tbody>";
$bgColors = ['transparent','yellow'];
$bgColor = 0;
echo "
<tr>
<td class='" . $bgColors[$bgColor] . "'>" . $rows[0]["size"] . "</td><td>" . $rows[0]["amount"] . "</td>
</tr>";
for($i = 1, $max = count($rows), $lastSize = $rows[0]; $i < $max; $lastSize = $rows[$i], $i++) {
if($rows[$i]["size"] !== $lastSize["size"])
$bgColor = ($bgColor + 1) % 2;
echo "
<tr>
<td style='background-color:" . $bgColors[$bgColor] . "'>" . $rows[$i]["size"] . "</td><td>" . $rows[$i]["amount"] . "</td>
</tr>";
}
echo "
</tbody>
</table>";
And an unasked for JS solution (assuming you've printed out the table as usual)
var rows = document.querySelectorAll('#sizeTable tbody td[name=size]');
var bgColors = ['transparent','yellow'];
var bgColor = 0;
for(var i = 1, lastSize = rows[0], max = rows.length; i < max; lastSize = rows[i],i++) {
if(rows[i].innerHTML !== lastSize.innerHTML) {
bgColor = (bgColor + 1) % 2;
}
rows[i].style['background-color'] = bgColors[bgColor];
}
you can keep the current size on a variable and if it changes you can change the color.
<html>
<head><title> Sample - Menukz </title></head>
<body>
<?php
/* Sample data array with size and amount */
$product['product123'] = array
(
array("size"=>"1", "amount"=>10),
array("size"=>"1", "amount"=>50),
array("size"=>"2", "amount"=>10),
array("size"=>"2+", "amount"=>10),
array("size"=>"3", "amount"=>40),
array("size"=>"3+", "amount"=>25),
array("size"=>"3+", "amount"=>40),
array("size"=>"4+", "amount"=>25)
);
$pre_size=0;
$pre_init=1;
echo "<table>";
foreach($product['product123'] as $row)
{
echo "<tr>";
/* Initialize */
if(strcmp($pre_size, $row['size']) !== 0 && $pre_init ===1)
{
$pre_size = $row['size'];
$pre_init = 0;
}
/* Change track */
if (strcmp($pre_size, $row['size']) !== 0 && $pre_init ===0)
{
echo "<td>Changed ... </td><td>". $row['size'] . "</td><td>" . $row['amount'] . "</td>";
$pre_size = $row['size'];
}
else
{
echo "<td>Not Changed ... </td><td>". $row['size'] . "</td><td>" . $row['amount'] . "</td>";
}
echo "</tr>";
}
?>
</body>
</html>
Thanks all for the proposed solutions. Berriel's MCVE works like a charm! However Stack doesn't let me +1 the answer yet.
I have one additional question:
I also have a second table in which the output of the first column can be any article code consisting of 10 chars limited to [a-z][0-9]. Since there is no predefined scheme such as in the Size table, I can't hardcode/predict any output like in most of the proposed solutions. However I still want to color the rows it in the same way described in my opening post.
I am not familiar with Stored Procedures or PDO in mysql. Is there any way to work around arrays with predefined content and still achieve the color grouping of rows with the same article code?
You can accomplish this using a nested repeat region.
First select your product by group WHERE product = 'product123' GROUP BY size
<?php
require ('conn.php');
try {
$prod = 'product123';
$sql = "SELECT * FROM sizes WHERE product=:prod GROUP BY size";
$query = $conn->prepare($sql);
$query->bindValue(':prod', $prod, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die('failed!');
}
?>
Then get all the products in each group ordered by amount inside a nested repeat region.
Each "grouped row" will alternate colors.
<table width="200" border="0" cellspacing="0" cellpadding="5">
<tr>
<td>Size</td>
<td>Amount</td>
</tr>
<?php
$i = 0;
do {
$i = $i + 1;
if ($i % 2 == 0){
echo '<tr bgcolor=#E4E4E4><td colspan="2">';
} else {
echo '<tr bgcolor=#EEEEEE><td colspan="2">';
}
try {
$group = $row['size'];
$sql = "SELECT * FROM sizes WHERE size=:group ORDER BY amount ASC";
$nested = $conn->prepare($sql);
$nested->bindValue(':group', $group, PDO::PARAM_INT);
$nested->execute();
$row_nested = $nested->fetch(PDO::FETCH_ASSOC);
$totalRows_nested = $nested->rowCount();
} catch (PDOException $e) {
die('nested failed');
}
echo '<table border="0" cellpadding="0" cellspacing="0" width="200">';
do {
echo '<tr><td width="100">'.$row_nested['size'].'</td><td width="100">'.$row_nested['amount'].'</td></tr>';
} while ($row_nested = $nested->fetch(PDO::FETCH_ASSOC));
echo '</table>';
echo '</td></tr>';
} while ($row = $query->fetch(PDO::FETCH_ASSOC));
?>
</table>
I am trying to apply css class for dynamic rows in php. But its not happening. Here is my code
please someone suggest me where i am going wrong. I have declared a counter for rows but not getting where to increment its count.
<table width='100%' border='0' cellspacing='0' cellpadding='2'>
<tr>
<td class='tddash'>10 latest unpaid customer invoices</td>
</tr>
<tr>
<td valign='top'>";
$SQL = "SELECT salesorders.orderno,
debtorsmaster.name,
custbranch.brname,
salesorders.customerref,
salesorders.orddate,
salesorders.deliverydate,
salesorders.deliverto,
salesorders.printedpackingslip,
salesorders.poplaced,
SUM(salesorderdetails.unitprice*salesorderdetails.quantity*(1-salesorderdetails.discountpercent)/currencies.rate) AS ordervalue
FROM salesorders INNER JOIN salesorderdetails
ON salesorders.orderno = salesorderdetails.orderno
INNER JOIN debtorsmaster
ON salesorders.debtorno = debtorsmaster.debtorno
INNER JOIN custbranch
ON debtorsmaster.debtorno = custbranch.debtorno
AND salesorders.branchcode = custbranch.branchcode
INNER JOIN currencies
ON debtorsmaster.currcode = currencies.currabrev
WHERE salesorderdetails.completed=0
GROUP BY salesorders.orderno,
debtorsmaster.name,
custbranch.brname,
salesorders.customerref,
salesorders.orddate,
salesorders.deliverydate,
salesorders.deliverto,
salesorders.printedpackingslip,
salesorders.poplaced
ORDER BY salesorders.orderno";
$SalesOrdersResult1 = DB_query($SQL,$db);
echo "<table width='100%' celpadding='2' class='selection'><tbody>";
$TableHeader = "<tr><th> Customer </th><th>Order Date</th><th>Delivery Date</th><th>Delivery To</th><th>Order Total</th></tr> ";
$k = 0;
while ($row = DB_fetch_array($SalesOrdersResult1))
{
if ($k == 1){
echo '<tr class="EvenTableRows">';
$k = 0;
} else {
echo '<tr class="OddTableRows">';
$k = 1;
}
$FormatedOrderValue1 = locale_number_format($row['ordervalue'],$row['currdecimalplaces']);
//$TotalOrderValue = $array_sum($FormatedOrderValue1);
//$FormatedOrderValue1 = locale_number_format($myrow['ordervalue'],$_SESSION['CompanyRecord']['decimalplaces']);
$FormatedOrderDate = ConvertSQLDate($row['orddate']);
$FormatedDelDate = ConvertSQLDate($row['deliverydate']);
echo " <td> " . $row['name'] . " </td>";
echo " <td>$FormatedOrderDate</td><td>$FormatedDelDate</td><td> " . $row['deliverto'] . " </td><td>$FormatedOrderValue1</td> ";
}
//echo "<tr><td colspan='3'>Total</td><td colspan='2'>$TotalOrderValue</td></tr></tbody>";
//echo $array_sum($FormatedOrderValue1);
echo "</table>";
echo"</td>
</tr>
</table>
Try to put this inside your while loop.
if ($k == 1){
echo '<tr class="EvenTableRows">';
$k = 0;
} else {
echo '<tr class="OddTableRows">';
$k = 1;
}
If you want decorate your table, and you can use css use it. Don't use server side language
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
Three issues with your code (four if you count the fact that you have a massive amount of HTML that should be moved outside of being echo'ed within php)
1) You have no $k++; to increment your $k value
2) You have a "tr" within the $row['name'] line that needs to be removed.
3) You need to move the entire if($k) block INSIDE of your while() loop.
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();
?>
I have a small PHP function that is called from one of my pages.
function ratingDetails($uid, $align, $width) {
$queryFull = "SELECT * FROM rating WHERE uid = $uid";
$resultFull = mysql_query($queryFull);
//START DISPLAY TABLE IF RESULTS
if(mysql_num_rows($resultFull) > 0) {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\" width=\"550\">\n";
echo "<tr bgcolor=\"#6699cc\"><th>STARS</th><th>DATE RATED</th><th>COMMENT</th><th>RATED BY</th></tr>\n";
while($rowFull = mysql_fetch_array($resultFull)) {
$rating = $rowFull['rating'];
$comment = $rowFull['comment'];
$datePosted = date("M j, Y", $rowFull['date']);
$rid = $rowFull['raterID'];
$rater = getUsername($rid);
//SHOW STARS
if($rating == 0) { $stars = "notYet.jpg"; }
if($rating == 1) { $stars = "starOne.jpg"; }
if($rating == 1.5) { $stars = "starOneHalf.jpg"; }
if($rating == 2) { $stars = "starTwo.jpg"; }
if($rating == 2.5) { $stars = "starTwoHalf.jpg"; }
if($rating == 3) { $stars = "starThree.jpg"; }
if($rating == 3.5) { $stars = "starThreeHalf.jpg"; }
if($rating == 4) { $stars = "starFour.jpg"; }
if($rating == 4.5) { $stars = "starFourHalf.jpg"; }
if($rating == 5) { $stars = "starFive.jpg"; }
//DISPLAY IT ALL
echo "<tr><td width=\"10\"><img src=\"/images/rating/$stars\" width=\"105\" height=\"20\" /></td>";
echo "<td width=\"75\" align=\"center\">$datePosted</td><td>$comment</td><td width=\"85\">$rater</td></tr>\n";
}//END WHILE
echo "</table>\n";
} //END IF
else {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"8\" width=\"550\">\n";
echo "<tr><td align=\"center\"><span class=\"blue\">NO REVIEWS OR RATINGS FOR THIS DISTRIBUTOR</span></td></tr></table>\n";
} //END IF ELSE
}
But when it runs in IE (7 or 8), it throws this error:
A script on this page is causing Internet Explorer to run slowly. Bla bla bla...
I call this function from two pages and both cause the same error. If I remove the call from the page, the page loads fine.
There is no javascript involved with the pages in question...
Help, help, help... I don't have much hair left...
Rick
What's happening is that it's taking a long time to execute your script. IE is waiting for output from the server but it's taking a long time.
You may want to try either a call to flush() every row (or maybe every 25 rows using the modulus operator) or using ob_implicit_flush() to turn on implicit flushing. That way you have data continually coming back to the browser (I assume you have a huge amount of data). You probably will also need to call set_timeout(0) to disable the 30 second time limit on your script.
The first thing I would do is get rid of all those IF statements for the stars, either using an array for them or a switch statement, either of which would reduce the processing required for your script. An array would be my approach. Your code would look something like the following:
function ratingDetails($uid, $align, $width) {
$queryFull = "SELECT * FROM rating WHERE uid = $uid";
$resultFull = mysql_query($queryFull);
// Declare the array for the stars.
$astars = array(
0=> "notYet.jpg",
1=> "starOne.jpg",
1.5=> "starOneHalf.jpg",
2=> "starTwo.jpg",
2.5=> "starTwoHalf.jpg",
3=> "starThree.jpg",
3.5=> "starThreeHalf.jpg",
4=> "starFour.jpg",
4.5=> "starFourHalf.jpg",
5=> "starFive.jpg"
);
//START DISPLAY TABLE IF RESULTS
if(mysql_num_rows($resultFull) > 0) {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\" width=\"550\">\n";
echo "<tr bgcolor=\"#6699cc\"><th>STARS</th><th>DATE RATED</th><th>COMMENT</th><th>RATED BY</th></tr>\n";
while($rowFull = mysql_fetch_array($resultFull)) {
$rating = $rowFull['rating'];
$comment = $rowFull['comment'];
$datePosted = date("M j, Y", $rowFull['date']);
$rid = $rowFull['raterID'];
$rater = getUsername($rid);
$stars = $astars[$rating];
//DISPLAY IT ALL
echo "<tr><td width=\"10\"><img src=\"/images/rating/$stars\" width=\"105\" height=\"20\" /></td>";
echo "<td width=\"75\" align=\"center\">$datePosted</td><td>$comment</td><td width=\"85\">$rater</td></tr>\n";
}//END WHILE
echo "</table>\n";
} //END IF
else {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"8\" width=\"550\">\n";
echo "<tr><td align=\"center\"><span class=\"blue\">NO REVIEWS OR RATINGS FOR THIS DISTRIBUTOR</span></td></tr></table>\n";
} //END IF ELSE
The decimals may cause a problem in the array; if so, you can enclose the keys in quotes; e.g., "1.5"=>"starOneHalf.jpg"
The other thing you could do is create a variable for the HTML output instead of echoing the output every line, and then just echo the output at the end.
I found my problem...
The table within my function was assigned a css class. This particular css class contained a behavior, which called PIE.htc. Apparently, this caused some sort of IE melt down whenever it was called. I removed PIE (bummer, no more rounded corners or shadows in IE) and my problem is solved!!!
Thanks to everyone who provided assistance along the way!!!