HTML Table Change Row to Column For loop - php

I need to attach two tables.
First loop is perfect,
but second For-loop table goes to the Bottom.
I need to attach that bottom table to that previous one.
Can anyone please solve this problem?
Any Solution would be appreciated, so suggest something to solve this.
<?php
include 'pappu.php';
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
$grab=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/USDT');
$json = json_decode($grab, true);
$usd= $json['Data'][3]['AskPrice'];
$grabb=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/USDT');
$jsonss = json_decode($grabb, true);
$dogeusd= $jsonss['Data'][8]['AskPrice'];
$grabsz=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/DOGE');
$jsonsz = json_decode($grabsz);
$grabs=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/BTC');
$jsons = json_decode($grabs);
echo "<table border=1>";
echo "<th>BTC EXCHANGE</th>";
if($jsons)
foreach ($jsons->Data as $sam){
$market= $sam->Label . "\n";
$link= $sam->AskPrice . "\n";
echo "<tr><td>$market</td>";
$link = number_format($link, 8);
echo "<td>$link" ;
echo '($';
echo number_format($link * $usd, 6) ;
echo ')';
echo "</td></tr>";
}
echo "<th>DOGE EXCHANGE</th>";
foreach ($jsonsz->Data as $sam){
$market= $sam->Label . "\n";
$link= $sam->AskPrice . "\n";
echo "<tr><td>$market</td>";
$link = number_format($link, 8);
echo "<td>$link" ;
echo '($' ;
echo number_format($link * $dogeusd, 6) ;
echo ')';
echo "</td></tr>";
}
echo "</table>";
?>

First set the table headers (<th>), then set the table body if you want all the headers to appear inline.
You can then make arrays for the rows of the two tables and just output for each row.
Note: In case your $btc and $doge arrays have a different amount of rows or are not in the same order you then might have to create a third array by combining the two, then loop over that.
echo '<table border="1">
<tr>
<th colspan="2">BTC EXCHANGE</th>
<th colspan="2">DOGE EXCHANGE</th>
</tr>';
// prepare the rows
$btc = array();
$doge = array();
if($jsons)
{
foreach ($jsons->Data as $sam)
{
$number = (float) $sam->AskPrice;
array_push($btc, array($sam->Label, number_format($number,8) ));
}
foreach ($jsonsz->Data as $sam)
{
$number = (float) $sam->AskPrice;
array_push($doge, array($sam->Label, number_format($number,8) ));
}
// assuming count($btc) and count($doge) are the same
for($i=0; $i< count($btc); $i++)
{
echo '<tr>
<td>'.$btc[i][0].'</td>
<td>'.$btc[i][1].' ($'.number_format($btc[i][1] * $usd, 6).')</td>
<td>'.$doge[i][0].'</td>
<td>'.$doge[i][1].' ($'.number_format($doge[i][1] * $usd, 6).')</td>
</tr>';
}
}
echo '</table>';
?>

You have two <th> cells which should be in a table row <tr>:
echo "<th>BTC EXCHANGE</th>";
and
echo "<th>DOGE EXCHANGE</th>";
Change your code to:
echo "<tr><th>BTC EXCHANGE</th></tr>";
and
echo "<tr><th>DOGE EXCHANGE</th>";

Related

How can i add multiple images using php powerpoint library?

Can u pls tell me how to bind multiple images in powerpoint using php powerpoint library? In the below code i used foreach loop to add multiple images in powerpoint but only one image is adding so pls help me.
<?php
require_once("db_config.php");
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPPowerPoint.php';
include 'PHPPowerPoint/IOFactory.php';
?>
<html>
<h3 align="center">Welcome <?php echo $_SESSION['user_name'];?>
<br>
Logout
</h3>
<body>
<?php
echo "<div align='center'>";
echo "<form method='post' action=''>";
echo "<table align='center' border='1'>
<tr>
<th></th>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>UserName</th>
</tr>";
$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><input type='checkbox' name='user_id[]' value='".$row['user_id']."' /> </td>";
echo "<td>" . $row['user_id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['user_name'] . "</td>";
echo "</tr>";
}
echo "</table><br>";
echo "<input type='submit' name='submit' value='Export PPT' />";
echo "</form></div>";
?>
</body>
</html>
<?php
if(isset($_POST['submit']) && isset($_POST['user_id'])){
$user_id = $_POST['user_id'];
foreach($user_id as $selected){
echo $selected."</br>";
$result = mysql_query("SELECT * FROM users WHERE user_id ='".$selected."'");
$row = mysql_fetch_array($result);
$img = '<img src="images/'.$row["image_name"].'" height="200" width="300" />';
$objPHPPowerPoint = new PHPPowerPoint();
// block sets slide logo.
$currentSlide = $objPHPPowerPoint->getActiveSlide();
$shape = $currentSlide->createDrawingShape();
$shape->setPath('images/'.$row["image_name"]);
$shape->setWidth(640);
$shape->setHeight(480);
$shape->setOffsetX(10);
$shape->setOffsetY(10);
// block sets text for first slide.
$shape = $currentSlide->createRichTextShape();
$shape->setHeight(700);
$shape->setWidth(600);
$shape->setOffsetX(10);
$shape->setOffsetY(500);
$shape->getAlignment()->setHorizontal( PHPPowerPoint_Style_Alignment::HORIZONTAL_CENTER );
$textRun = $shape->createTextRun('FirstName:'.$row["first_name"].' Lastname:'.$row["last_name"].' UserName:'.$row["user_name"]);
$textRun->getFont()->setBold(true);
$textRun->getFont()->setSize(30);
$textRun->getFont()->setColor( new PHPPowerPoint_Style_Color( '#FFFF' ) );
// block sets text for first slide ends.
$filename = str_replace('.php', '.pptx', __FILE__);
$newname = "PresentationReport-" . date('Y-m-d-H-i-s') . ".pptx";
$objWriter = PHPPowerPoint_IOFactory::createWriter($objPHPPowerPoint, 'PowerPoint2007');
$objWriter->save(str_replace('.php', '.pptx', __FILE__));
// block to download file.
header("Pragma: no-cache");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=" . $newname);
ob_clean();
flush();
readfile($filename);
exit();
}
}
else
{
echo "<div align='center'>Please choose the user</div>";
exit;
}
?>
How can i add multiple images using php powerpoint library?
Two troubles can be indentified in your snippet:
1 - You're calling "new Powerpoint" to each element in foreach, and due this
you always override the previous slide.
2 - You're positioning your shapes in the same x/y offset:
$shape->setOffsetX(10);
$shape->setOffsetY(10);
So in the foreach all shapes will be stacked.
To a functional solution you'll need to mount a valid algorithm like:
I'll have 4 photos by slide for example so:
$resultsFromDataBase = $resultsFromDataBase;
// Array chunk to create a "logic" 4 photos ... jump to the new slide
$resultsBySlide = array_chunk($resultsFromDataBase, 4);
// Each photo needs your independent X offset
// Note the fake values, you need to calculate them
$positionsByIndex = [
0 => 10,
1 => 20,
2 => 30,
3 => 40
];
foreach ($resultsBySlide as $i => $rows) {
// 4 photos -> Jump the slide and create another one
$ppt->createSlide();
// SlideCount -1 gets your current index
$slideIndex = $ppt->getSlideCount()-1;
$currentSlide = $objPHPPowerPoint->getActiveSlide();
foreach ($rows as $position => $row) {
$shape = $currentSlide->createDrawingShape();
$shape->setPath('images/'.$row["image_name"]);
$shape->setWidth(640);
$shape->setHeight(480);
$shape->setOffsetX($positionsByIndex[$position]); // Here the point
$shape->setOffsetY(10);
}
}
And the last point but not less important: Don't use mysql_* in your project
use: PDO or mysqli_* instead

Change background color of a cell when next value is different from the preceding one

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>

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();
?>

Delete index session in PHP

I have question referring to the session in PHP.
I've coded in PHP for setting the session and I want to delete it , but I got some errors and confusing with using the UNSET(variable $_SESSION). Perhaps anyone could help me to show what should I do with this matter. Thanks in advance
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['index'] = 0
$_SESSION['chart'][0]['type'] = $type;
$_SESSION['chart'][0]['idanimal'] = $iddog;
$_SESSION['chart'][0]['price'] = $price;
printdata(); // <== this is the function to print out the data
All I want to do is just delete based on the index in this session
Here's the function :
function printdata()
{
$totalharga = 0;
if(is_array($_SESSION['chart']))
{
echo "<h3>"."Berikut adalah keranjang belanja anda" . "</h3>". "<br>";
$max = count($_SESSION['chart']);
$th1 = "<th>" . "No" . "</th>";
$th2 = "<th>" . "Animal Type" . "</th>";
$th3 = "<th>" . "ID Binatang" . "</th>";
$th4 = "<th>" . "Harga" . "</th>";
$th5 = "<th>" . "Hapus Data" . "</th>";
echo "<table border=1>";
echo "<tr>";
echo $th1 ;
echo $th2;
echo $th3;
echo $th4;
echo $th5;
echo "</tr>";
for ($indexo = 0; $indexo < $max; $indexo++)
{
echo "<tr>";
echo "<td>" . $indexo."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['type']."</td>";
echo "<td>" . $_SESSION['chart'][$indexo]['idanimal']."</td>";
echo "<td>" . "Rp. " . $_SESSION['chart'][$indexo]['harga']. ",-" ."</td>";
echo "<td>" . "<a href='deletesession.php?session=$indexo'>" ."Proses ". "</a>"."</td>";
$totalharga += $_SESSION['chart'][$indexo]['harga'];
echo "</tr>";
}
echo "</table>" . "<br/>";
echo "<blockquote>" . "Total Pembelian Item Yang Anda Pesan =". "<h2>". "Rp." . $totalharga . ",-" ."</h2>" . "</blockquote>";
}else
{
echo "Chart is still Empty";
}
}
I've already tried this :
Suppose that there is a chart already filled by the contents then I tried to delete within this code, I've received error with the unset variable
unset($_SESSION['chart'][1])
Thank you
I spot several things that could be improved in your code:
Don't echo in your functions, return instead (then echo what the function returns). This gives you more flexibility regarding what you do with your result.
PHP has a built-in loop for iterating arrays, the foreach loop. You should be using that instead of for.
So here's what I have:
function print_session_data($session) {
if (!is_array($session)) {
return "Array is empty";
}
$table_data = "";
$total_harga = 0;
foreach ($session as $index => $data) {
$table_data .= <<<TABLE_DATA
<tr>
<td>$index</td>
<td>{$data["type"]}</td>
<td>{$data["idanimal"]}</td>
<td>Rp. {$data["harga"]}</td>
<td>Proses</td>
</tr>
TABLE_DATA;
$total_harga += $data["harga"];
}
$result = <<<RESULT
<h3>Berikut abalah keranjang belanja anda</h3>
<table border="1">
<thead>
<tr>
<th>No</th>
<th>Animal Type</th>
<th>ID Binatang</th>
<th>Harga</th>
<th>Hapus Data</th>
</tr>
</thead>
<tbody>
$table_data
</tbody>
</table>
<blockquote>Total Pembelian Item Yang Anda Pesan = <strong>Rp. $total_harga</strong></blockquote>
RESULT;
return $result;
}
$_SESSION['chart'] = array();
$_SESSION['chart'][0]['type'] = "Type";
$_SESSION['chart'][0]['idanimal'] = 6;
$_SESSION['chart'][0]['price'] = '$25';
$_SESSION['chart'][0]['harga'] = 25;
echo print_session_data($_SESSION["chart"]); // <== this is the function to print out the data
Suppose that there is a chart already filled by the contents then I
tried to delete within this code, I've received error with the unset
variable unset($_SESSION['chart'][1])
From what I can see from your code the best way to unset the data correctly is as follow:
DEMO.
You have to check if the $_SESSION['chart'][0] was set before using the session variable index again. If it $_SESSION['chart'] array still contains other indexes then you can call printdata(); else indicate that the session was empty.

Headers downloading actual page content, not the csv file I've constructed

My goal here is to have the browser download a csv file using headers to do it. For some reason yet to be determined, the browser seems to be downloading the HTML content of the current page (and not the contents of the array I've given it).
Here is the code I've been using:
$arr1 = array(array("1","2","3","4"),array("2","1","6","6"));
$tmp_handle = fopen('php://memory', 'r+');
fputcsv($tmp_handle, $arr1);
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
rewind($tmp_handle);
echo stream_get_contents($tmp_handle);
I've followed the instructions of many articles / SO questions I've read and I don't see what's wrong with this code.
I of course appreciate any help that I can get here!
Here is the complete code (upon request):
<?php
global $wpdb;
// Get total number of active referrers
$referrer_check = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."referrer");
$num_of_referrers = 0;
foreach ( $referrer_check as $check)
{
$num_of_referrers++;
}
// Get total number of referral transactions
$num_of_referrals = 0;
$num_referral_check = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."referrer_transactions");
foreach ( $num_referral_check as $check)
{
$num_of_referrals++;
}
// Check for the top referrer
$top_referrer = $wpdb->get_row("SELECT referrer_id, count(*) as row_count FROM ".$wpdb->prefix."referrer_transactions GROUP BY referrer_id ORDER BY COUNT(*) DESC");
$top_referrer_result = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."referrer WHERE referrer_id = $top_referrer->referrer_id");
// Construct the table
// Create array for second table
$ref_transactions_table_arr = array(
array("Referee Name", "Referee ID", "Referee Sign Up", "Referee Email","Referrer ID","Referrer Name"));
foreach ($num_referral_check as $check)
{
$ref_transactions_table_arr[] = array(
$wpdb->get_var("SELECT billing_name FROM ".$wpdb->prefix."pmpro_membership_orders WHERE user_id = $check->buyer_id"),
$check->buyer_id,
$wpdb->get_var("SELECT user_registered FROM ".$wpdb->prefix."users WHERE ID = $check->buyer_id"),
$wpdb->get_var("SELECT user_email FROM ".$wpdb->prefix."users WHERE ID = $check->buyer_id"),
$wpdb->get_var("SELECT referrer_id FROM ".$wpdb->prefix."referrer WHERE referrer_id = $check->referrer_id"),
$wpdb->get_var("SELECT referrer_name FROM ".$wpdb->prefix."referrer WHERE referrer_id = $check->referrer_id")
);
}
// Create array for first table
$active_ref_table_arr = array(
array('Referrer Name', 'Referrer ID', '# of Referrals', 'Address','Referrer Email','Lifetime Referrals'));
foreach ( $referrer_check as $check)
{
$active_ref_table_arr[] = array(
$check->referrer_name,
$check->referrer_id,
$wpdb->get_var("SELECT count(*) FROM ".$wpdb->prefix."referrer_transactions WHERE referrer_id = $check->referrer_id"),
$check->referrer_street . " " . $check->referrer_city . ", " . $check->referrer_state . " " . $check->referrer_zip,
$wpdb->get_var("SELECT user_email FROM ".$wpdb->prefix."users WHERE ID= $check->referrer_id"),
$wpdb->get_var("SELECT count(*) FROM ".$wpdb->prefix."referrer_transactions WHERE referrer_id = $check->referrer_id")
);
}
// Download file
if(isset($_POST['export_tbl_one']))
{
$csvData = array(
array("1","2","3","4"),
array("2","1","6","6")
);
$fp = fopen('php://memory', 'w+');
/*foreach ($csvData as $row) {
fputcsv($fp, $row);
}*/
fputcsv($fp,$csvData);
rewind($fp);
$csvFile = stream_get_contents($fp);
fclose($fp);
header('Content-Type: text/csv');
header('Content-Length: '.strlen($csvFile));
header('Content-Disposition: attachment; filename="file.csv"');
exit($csvFile);
}
?>
<div class="nav">
<ul>
<li class="first">Total Referrers: <? echo $num_of_referrers; ?></li>
<li>Total Referals: <? echo $num_of_referrals; ?></li>
<li>Top Referrer: <? echo $top_referrer->referrer_id . ", " . $top_referrer_result->referrer_name . "(" . $top_referrer->row_count . ")"; ?></li>
<li>
<form method="POST" action="http://keepmecertified.com/acp">
<input type="submit" value="click me" name="export_tbl_one"/>
</form>
</li>
</ul>
</div>
<br>
<table class="table">
<caption>Referrer Transactions</caption>
<?
$num = 0;
foreach($ref_transactions_table_arr as $fields)
{
echo "<tr>";
foreach($fields as $data)
{
if($num == 0)
{
echo "<th class=\"ref_head\">$data</th>";
}
else
{
echo "<td>$data</td>";
}
}
echo "</tr>";
if($num == 0)
{
$num++;
}
}
?>
</table>
<table class="table">
<caption>Active Referrers</caption>
<?
$num = 0;
foreach($active_ref_table_arr as $fields)
{
echo "<tr>";
foreach($fields as $data)
{
if($num == 0)
{
echo "<th class=\"ref_head\">$data</th>";
}
else
{
echo "<td>$data</td>";
}
}
echo "</tr>";
if($num == 0)
{
$num++;
}
}
?>
</table>
Try this code:
$csvData = array(
array("1","2","3","4"),
array("2","1","6","6")
);
$fp = fopen('php://memory', 'w+');
foreach ($csvData as $row) {
fputcsv($fp, $row);
}
rewind($fp);
$csvFile = stream_get_contents($fp);
fclose($fp);
header('Content-Type: text/csv');
header('Content-Length: '.strlen($csvFile));
header('Content-Disposition: attachment; filename="file.csv"');
exit($csvFile);
I have looped the data to build the CSV as your code would not produce the result you expect. I have also retrieved the file as a string before outputting - this is just a nicety to add a Content-Length header. I have also - and this is the important bit - called exit to output the data, to prevent any more code being executed any prevent and HTML after this code being output.
If you are using this code and still having a problem, then the code is not being called - you should check any if statements etc that this code is wrapped in.
This is way late but let's hope this unblocks someone.
Use ob_end_clean() to clean out other buffers on the page.
Start with ob_end_clean(); and end with exit;
This way, only the output in between will be written to the file.

Categories