Custom simple pagination with jQuery and PHP - Finding myself stumped - php

So I'm working on my very first ever attempt at pagination (using simple Previous and Next buttons) on a for-fun project that I've undertaken. Below is all of the relevant code for my pagination system - I have left out the before and after, but I assure you that the table structure is valid.
Here is the jQuery I'm using with the elements I'm using to call the script:
<ul class="pager">
<li class="previous">< Previous</li>
<li class="next">Next ></li>
</ul>
<script>
$(document).ready(function() {
var page = 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
$('#pagination-prev').click(function() {
page = page - 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
});
$('#pagination-next').click(function() {
page = page + 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
});
});
</script>
When I viewed the page without the jQuery active, I saw 8 <tbody> elements filled with dummy data that had been properly classed and id'd by the PHP script. My issue is that when I view the page with the script active, it doesn't seem to be working out for me. It hides all .pagination-page elements as I want, but my output has nothing toggled to show. Below is the PHP that is generating the content that I am flipping through.
<?php
try {
$listed = $dbc->query("SELECT data1,data2,data3,data4 FROM `table` ORDER BY data3 DESC")->fetchAll(PDO::FETCH_BOTH);
$annPP = 15;
$totalRows = count($listed);
$lastPCount = $totalRows % $annPP;
$totalPages = ceil($totalRows/$annPP);
$place = 0;
for ($i=1;$i<=$totalPages;$i++) {
echo "<tbody class='pagination-page' id='page{$i}'>";
if ($i == $totalPages) {
// Only do the remaining rows
$pageMax = $place + $lastPCount;
} else {
// Do 15 rows
$pageMax = $i * 15;
}
for ($j=$place;$j<$pageMax;$j=$place) {
$row = $listed[$j];
echo "<tr>
<td style='width: 25%'>";
if ($isAdmin) {
echo '<label class="control-label"><input type="checkbox" name="delete[]" value="' . $row['0'] . '"> ';
}
echo "<a href='view.php?id={$row[0]}'>{$row[1]}</a>";
if ($isAdmin) {
echo '</label>';
}
echo "</td>
<td style='width: 60%'>{$row[2]}</td>
<td class='text-center' style='width: 15%'>";
$created = new DateTime($row[3]);
echo $created->format('Y/m/d') . "</td>
</tr>";
$place++;
}
echo "</tbody>";
}
}
?>
What did I miss? What's going on? Thanks!

Removing the .pagination-page to make my jQuery read as follows:
$("tbody[id='page" + page + "']").show;
Fixed the problem. Not quite sure I understand why this is, though.

Related

How to add +1 to var with href?

I have this quantity (var name: $Quantidade) displayed from a cart and need to add + and - hrefs to make it increase/decrease value.
Quantity:
quantity
Full table:
table
The quantity var always starts at 1.
All my attempts have failed.
Here is some code for the table (works if the + href is removed):
<table class="cart" width=700px cellpadding="0" cellspacing="0" style="border: 1px;" rules="none" align="center">
<tr height=40px align="center">
<td>Product</td>
<td>Price</td>
<td></td>
<td>Quantity</td>
<td></td>
<td>Delete</td>
</tr>
<?php
// Carrinho
$total=0;
foreach($_SESSION['venda'] as $Prod => $Quantidade):
$SqlCarrinho = mysqli_query($conect,"SELECT * FROM produto WHERE id= '$Prod'");
$ResAssoc = mysqli_fetch_assoc($SqlCarrinho);
echo '<tr height=40px align="center">';
echo '<td>'.$ResAssoc['descricao'].'</td>';
echo '<td>'.number_format($ResAssoc['preco'],2,",",".").'€</td>';
echo '<td>-</td>';
echo '<td>'.$Quantidade.'</td>';
echo '<td>+</td>';
echo '<td>x</td>';
$total += $ResAssoc['preco'] * $Quantidade;
echo '</tr>';
endforeach;
echo '<tr height=40px>';
echo '<td colspan="6" align="right">Total: '.number_format($total,2,",",".").'€</td>';
echo '</tr>';
echo'</table>';
Here is some code for the sessions I use:
session_start();
if(isset($_POST['more'])){ $_SESSION['venda'] [$_GET['par']] = $_GET['par'] + 1 ; }
if(isset($_SESSION['venda'])){}
else{ $_SESSION['venda'] = array(); }
if(isset($_GET['par'])){ $_SESSION['venda'] [$_GET['par']] = 1 ; }
if(isset($_GET['del'])){
$Del = $_GET['del'];
unset($_SESSION['venda'][$Del]);
Everything works until I add the + href, then it disformats the table:
broken table
I have confirmed its not a css error, the href is gone with/without css.
You need to remove the # in the link.
<a href="?more=true&par='.$Prod.'>+</a>
instead of
<a href="#?more=true&par='.$Prod.'>+</a>
When sending requests to your server, the browser ignores everything after the first #. Your GET parameters are not sent with the request currently.
Update
Check out the marked line. It resets venda → par every time par is set (which is always the case if you want to increase your value). Maybe you also want this to initialize the var. In this case you need to fix the if statement (if(!isset($_GET['par'])){ /* ... */ }). Venda gets reseted too.
session_start();
if(isset($_POST['more'])){ $_SESSION['venda'] [$_GET['par']] = $_GET['par'] + 1 ; }
if(isset($_SESSION['venda'])){}
else{ $_SESSION['venda'] = array(); }
// This line
if(isset($_GET['par'])){ $_SESSION['venda'] [$_GET['par']] = 1 ; }
if(isset($_GET['del'])){
$Del = $_GET['del'];
unset($_SESSION['venda'][$Del]);
Update 2
I think you want the code like this:
session_start();
// First, check if all vars are initialized
// Init if 'venda' is NOT set
if (!isset($_SESSION['venda'])) {
$_SESSION['venda'] = array();
}
// Init if 'venda['par'] is not set
if (isset($_GET['par']) && !isset($_SESSION['venda'][$_GET['par']])) {
$_SESSION['venda'][$_GET['par']] = 1;
}
// Run the updates/deletions
// Increase if 'more' is set
if (isset($_POST['more']) && isset($_GET['par'])) {
$_SESSION['venda'][$_GET['par']] += 1;
}
// Delete
if (isset($_GET['del'])) {
$Del = $_GET['del'];
unset($_SESSION['venda'][$Del]);
}

How to check the correct execution of the calling to a page using JQuery and XAMPP?

I state that I'm very inexperienced with web programming.
I'm trying to write a very simple web server in which suppliers must login to have access to a page that presents a table. In the table there are all the active orders for that supplier. Every row presents a list of fields: most of them are only readable, but the last three are also editable. The request I have to satisfy is that every time a supplier leaves an editable field, an update query runs to the database to update that field. I know, it's inefficient, but this is the request I've received.
My problem is that I've all already ready: the pages, the methods to generate the queries, etc...
...but when the page launches che ajax request to the saving page, nothing happens.
I've tried everything, I also tried to execute some very stupids examples find out on sites like w3school and other. Also the most stupid jquery function that try to call another page doesn't run, and I don't know why.
My questions are two:
is the below code right? I think it is, I'm not able to find out any error, but i'm not sure at this point.
the second one, is there a way to check if it is a problem of the pc, of the web server, or something else that does'nt wirk properly? The machine is not mine, so I'm not authorized to try to install or uninstall to check the status of every component.
Thank you all.
Here the code of the client side page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<TITLE>Orders</TITLE>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
var temp = "";
function saveContext(obj) {
temp = "";
temp = obj.value;
}
function handleCheckbox(obj) {
if (obj.value == 1)
{
obj.value = "0";
}
else
{
obj.value = "1";
}
var values = obj.id.split("//");
updateDB("UPDATE ordini SET " + values[3] + "=\"" + obj.value + "\" WHERE idFornitore=\"" + values[0] + "\" and idOrdine=\"" + values[1] + "\" and codiceArticolo=\"" + values[2] + "\"");
}
// Validates that the input string is a valid date formatted as "aaaa-mm-dd"
function isValidDate(dateString) {
// First check for the pattern aaaa-mm-dd
if(!/^\d{4}-\d{2}-\d{2}$/.test(dateString))
return false;
// Parse the date parts to integers
var parts = dateString.split("-");
var day = parseInt(parts[2], 10);
var month = parseInt(parts[1], 10);
var year = parseInt(parts[0], 10);
// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
return false;
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
};
function handleNota(obj) {
var values = obj.id.split("//");
updateDB("UPDATE ordini SET " + values[3] + "=\"" + obj.value + "\" WHERE idFornitore=\"" + values[0] + "\" and idOrdine=\"" + values[1] + "\" and codiceArticolo=\"" + values[2] + "\"");
}
function handleData(obj) {
var values = obj.id.split("//");
if(isValidDate(obj.value) == true)
{
updateDB("UPDATE ordini SET " + values[3] + "=\"" + obj.value + "\" WHERE idFornitore=\"" + values[0] + "\" and idOrdine=\"" + values[1] + "\" and codiceArticolo=\"" + values[2] + "\"");
}
else
{
alert("Insert a valid date");
document.getElementById(obj.id)
obj.value=temp;
obj.Focus();
}
}
function updateDB(sql) {
$.ajax({
type: "POST",
url: "/save.php",
data: {
query: sql;
},
success: function(output){
alert(output);
},
error: function(jqxhr, status, exception) {
alert('Exception: ', status);
}
});
}
</script>
</head>
<body>
<?php include "config.php"; $temp=""; ?> <!-- <==import code for database connection -->
<div id="wrap">
<div id="main">
<div id="colonna-1"><img src="immagini/logosx.png" height="123" width="210" alt="Logo">
</div>
<div id="colonna-2" style="text-align:center">
<div id="contenitore">
<div id="utente">
<?php
$user=$_SESSION['idFornitore'];
?>
<table id="enter">
<tr height="123"></tr>
<tr>
<td><img id="user" src="immagini/user.png" height="20" width="20"></td>
<td align="left"> Benvenuto </td>
<td align="letf"><?php echo"$user"." "?></td>
<td align="left">Logout</td>
</tr>
</table>
</div> <!--utente-->
<div id="contenuto">
<?php
$sql = "SELECT * FROM ordini WHERE idFornitore='$user' ORDER BY idOrdine, codiceArticolo ASC";
$result = mysqli_query($conn, $sql);
$numfields = mysqli_num_fields($result);
echo "<table id='elencoordini'><tr>";
for ($i=1; $i < $numfields; $i++)
{
echo '<th>'.ucwords(mysqli_fetch_field_direct($result, $i)->name).'</th>';
}
echo "</tr><br><br><br><br>\n";
$nr = mysqli_num_rows($result);
if ($nr != 0){
for($x = 0; $x < $nr; $x++){
while ($row= mysqli_fetch_array($result))
{
echo "<tr>";
for ($i=1; $i < $numfields-3; $i++)
{
echo '<th><input type="text" value="'.ucwords($row[$i]).'"readonly style="color:DimGrey"></th>';
}
if ($row[$i] == null)
{
echo '<th><input type="text" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i)->name.'" value="" style="font-weight: bold;" onclick="saveContext(this)" onfocusout="handleData(this)"></th>';
}
else
{
echo '<th><input type="text" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i)->name.'" value="'.ucwords($row[$i]).'" style="font-weight: bold;" onclick="saveContext(this)" onfocusout="handleData(this)"></th>';
}
if ($row[$i+1] == 1)
{
echo '<th><input type="checkbox" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i+1)->name.'" name="checkdate" value="1" checked onclick="handleCheckbox(this)"></th>';
}
else
{
echo '<th><input type="checkbox" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i+1)->name.'" name="checkdate" value="0" onclick="handleCheckbox(this)"></th>';
}
if ($row[$i+2] == null)
{
echo '<th><input type="text" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i+2)->name.'" value="" style="width: 400px; font-weight: bold;" maxlength="4000" onfocusout="handleNota(this)"></th>';
}
else
{
echo '<th><input type="text" id="'.$row[0]."//".$row[1]."//".$row[3]."//".mysqli_fetch_field_direct($result, $i+2)->name.'" value="'.ucwords($row[$i+2]).'" style="width: 400px; font-weight: bold;" maxlength="4000" onfocusout="handleNota(this)"></th>';
}
echo "</tr>\n";
}
}
echo "</table><br><br><br><br>\n";
}
else{
echo "No records found!";
}
// Close db conn
mysqli_close($conn);
?>
</div> <!--contenuto-->
</div><!--contenitore-->
</div><!--colonna2-->
<div id="colonna-3">
</div><!--colonna3-->
</div> <!--main-->
</div> <!--wrap-->
<?php include "footer.inc.php"?>
</body>
</html>
and here is the code of the server side page that, in my intention, has to update the database:
<?php
include "config.php"; //import code for database connection
$query=$_POST['query'];
if (mysqli_query($conn, $query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
?>
In generell I would do some backtracing basically since you have the echos in your php file you should check wether or not they are in the alert window since you use an ajax post to call the file. If you receive some output in your alert window that is defined in the php file, then you know for sure that your php file is being called correctly maybe you echo out the query that is being sent sometimes an input that contains a quote -> ' can screw up the query.
So basically do some backtracing until you realize that something is not called properly and there you should find the error.
Also I strongly recommend to build a database adapter class and some controllers to handle the functionalities. Having mysql functions inside the html file is a huge no go.

How to Remember Checkbox/Radio-button Selection in a mulit-page form

We have a form that Span Across multiple pages and the form is full of checkboxes and radio-buttons. Requirement is that when a user navigates across multiple pages of the form, the user should be able to see the checkboxes and radio-buttons he has already Selected before the form Submit button is pressed.
I am copying the code segement that is used to generate the Checkboxes in the form - this is a Sample code Only.
<form action="car_model.php" method="post" name="car_form" id="car_form">
$q10 = "SELECT ...
$r10 = mysqli_query ($dbc, $q10);
if (mysqli_num_rows($r10) > 0) {
while ($row10 = mysqli_fetch_array($r10, MYSQLI_ASSOC))
{
echo '<p class="normal_text"><input type="checkbox" name="model_selection[]" value="' . $row10['model_id'] . '" onclick="return KeepCount()"; />' . $row10['car_model_name'] . '</p></br>';
}
}
</form>
if ($pages > 1) {
echo '<br /><p>';
// Determine what page the script is on:
$current_page = ($start/$display) + 1;
// If it's not the first page, make a Previous button:
if ($current_page != 1) {
echo 'Previous ';
}
// Make all the numbered pages:
for ($i = 1; $i <= $pages; $i++) {
if ($i != $current_page) {
echo '' . $i . ' ';
} else {
echo $i . ' ';
}
}
// If it's not the last page, make a Next button:
if ($current_page != $pages) {
echo 'Next';
}
echo '</p>';
}
I understand that JQuery is a Good tool for this purpose - how to use it?
If using server side session variables is not an option then you could implement it in such a way that when you click "next" instead of loading a new page you just hide the current content place holder of the visible part of the form and show the next one at it's place and the same when clicking back.
This can easily be done with jQuery. Here is a very simple example to get you started:
$("#next").click( function () {
$("#page1").hide();
$("#page2").show();
});
$("#back").click( function () {
$("#page1").show();
$("#page2").hide();
});
Fiddle
Good luck!

how to differentiate between these entries?

I have a new question about a project I had been working on. I was designing a grid with different colored cells. it has a hidden div which shows when a cell is clicked, however I realized that only one cell(the last one of it's type) will show. i.e. if I have 2 objects with the column "objaffinity" as 0 ("enemy") it will show both red cells on the grid, however only the last one will actually work.
how can I make it so that it will show the proper information for each cell?
here's my code:
mapgen.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="cellinfo.js"></script>
<script src="cmenu.js"></script>
<?php
require("sql.php");
$sql = <<<SQL
SELECT *
FROM `maps`
WHERE `objpresent` = 1
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
} // ran the query
//$xobj = array();
//$yobj = array();
$otype = array();
$oname = array();
$xyobj = array();
while($row = $result->fetch_assoc()){
$xyobj[$row['x']][$row['y']] = true;
$otype[$row['id']]=$row['objaffinity'];
$oname[$row['id']]=$row['object'];
}
// get the rows
$cellid=1;
//find whether the row is obstructed
for ($y = 0; $y < 20; $y++) {
echo '<tr>';
for ($x = 0; $x < 25; $x++) {
echo "<td>";
//Detect what type of object it is
if (isset($xyobj[$x][$y])) {
if($otype[$cellid] == 2)
{
echo "<a href='#'> <div class='foe'> </div><div class='foepopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
elseif($otype[$cellid] == 1)
{
echo "<a href='#'><div class='friend'></div><div class='friendpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
else
{
echo "<a href='#'> <div class='neutral'></div><div class='neutralpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
$cellid++;
}
echo '</td>';
}
echo '</tr>';
}
?>
Cellinfo.js:
$(document).ready(function(){
//initially hide all popups
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").hide();
//foebutton selected
$(".foe").on("click",function(e){
$(".friendpopup").hide();
$(".neutralpopup").hide();
$(".foepopup").show();
});
//close foe when selected
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
//neutral button pressed
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
//close neutral
$(".neutralpopup").on("click",function(e){
$(".neutralpopup").hide();
});
//friend button pressed
$(".friend").on("click",function(e){
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").show();
});
//close friend
$(".friendpopup").on("click",function(e){
$(".friendpopup").hide();
});
});
In your functions you use selectors, so for the script it does not matter which div was clicked.
Let me show you some examples:
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
It should be something like this rather:
$(".foepopup").on("click",function(e){
$(this).hide();
});
And another example:
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
Rewrite it like this:
$(".neutral").on("click",function(e){
var td_tag = $(this).parent().parent();
td_tag.children(".foepopup").hide();
td_tag.children(".friendpopup").hide();
td_tag.children(".neutralpopup").show();
});
Rewrite other code on your own. this is the element on which click was triggered. td_tag will contain parent cell of a div clicked. After that, children method will allow you to find needed elements already inside specific cell.
Good luck!

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