Exporting a dynamic table to Excel in PHP - php

I have a large table with an unknown amount of columns that I want to be able to export to MS Excel via a download link. I have done this before with no issues. However, that was when I had a known number or columns. I currently am able to successfully send data to an Excel file. The table headers display correctly across the top of the table. The problem is with the data. Instead of placing the data across the page in the correct columns, it is putting it all in the first column. Here is part of my code:
while($row = mysql_fetch_row($result))
{
// Loops through the results
for($i=0; $i < $num_cols; $i++)
{
// Prints out the data in a table cell
echo("<Td class='data'>$row[$i]</Td>");
$FileRecord = Array($row[$i]);
$exportFile->Export_Record($FileRecord);
}
}
Normally I do $FileRecord = Array($row[0], $row[1], ..., $row[n]) and everything works great, but I am not sure how to do that if I don't know how many columns there are. Any help would be great!
I am not using any library. $exportFile is from a function that I am using. It looks like this:
class CSV_File {
private $out='';
private $name='';
private $column_names="";
private $count = 0;
//Creates the file name and the header columns
function __Construct($buf, $names) {
$GLOBALS["name"] = $buf;
$GLOBALS["column_names"] = ($names."\n");
}
public function Export_Record($array) {
if (!is_array($array))
throw new Exception("NOT AN ARRAY");
for ($i = 0; $i <= count($array); $i++) {
$GLOBALS["out"] .= $array[$i];
if ($i < count($array)-1) {
$GLOBALS["out"] .= ",";
}
}
$GLOBALS["out"] .= "\n";
$GLOBALS["out"]++;
}
public function ExportButton($align) {
$output = $GLOBALS["out"];
$filename = $GLOBALS["name"];
$columns = $GLOBALS["column_names"];
if ($align == null)
$align = "align";
echo(" <$align><form name=\"export\" action=\"export.php\" method=\"post\">
<button type=\"submit\" style='border: 0; background: transparent; font-size: 12px;font-weight:bold;'>
<img src = 'images/icon_csv.png' width = '16' height ='16' alt ='Download Data'> Download</button>
<input type=\"hidden\" value=\"$columns\" name=\"csv_hdr\">
<input type=\"hidden\" value=\"$filename\" name=\"fileprefix\">
<input type=\"hidden\" value=\"$output\" name=\"csv_output\">
</form></align>");
}
}
And then export.php looks like this:
if (isset($_POST['csv_hdr']))
{
$out .= $_POST['csv_hdr'];
$out .= "\n";
}
if (isset($_POST['csv_output']))
{
$out .= $_POST['csv_output'];
}
if (isset($_POST['fileprefix']))
{
$fname .= $_POST['fileprefix'];
}
//Now we're ready to create a file. This method generates a filename based on the current date & time.
$filename = $fname."_".date("Y-m-d_H-i",time());
//Generate the CSV file header
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
//Print the contents of out to the generated file.
print $out;
//Exit the script
exit;'

That's not an Excel table. It's an html table that you just happen to be feeding into Excel.
Your problem is that you're not starting a new table row for every record you're fetching, so everything just becomes a new cell in the first row.
You need something like
while($row = mysql_fetch_assoc($result)) {
echo '<tr>';
foreach($row as $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}

Related

I want to export an excel from mysql database. I want to have the column name from users with the help of check box

this is my normal CSV query. I want to take the column name from user input. like with a form containing checkbox or dropdown. how should I modify it? I have tried checkbox but isset($_POST["checkboxname"]) is not working.
<?php
include("../../../config.php");
//if(isset($_POST["submit"])){
$xls_filename = 'export_'.date('Y-m-d').'.xls'; // Define Excel (.xls) file name
$start_date=$_POST["date_time"];
$sql_ex = "Select device_name,description,card,device_module,uid FROM device";
$result = #mysql_query($sql_ex,$conn) or die("Failed to execute query:<br />" . mysql_error(). "<br />" . mysql_errno());
// Header info settings
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$xls_filename");
header("Pragma: no-cache");
header("Expires: 0");
/***** Start of Formatting for Excel *****/
// Define separator (defines columns in excel & tabs in word)
$sep = "\t"; // tabbed character
// Start of printing column names as names of MySQL fields
for ($i = 0; $i<mysql_num_fields($result); $i++) {
echo mysql_field_name($result, $i) . "\t";
}
print("\n");
// End of printing column names
// Start while loop to get data
while($row = mysql_fetch_row($result))
{
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result); $j++)
{
if(!isset($row[$j])) {
$schema_insert .= "NULL".$sep;
}
elseif ($row[$j] != "") {
$schema_insert .= "$row[$j]".$sep;
}
else {
$schema_insert .= "".$sep;
}
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
Firstly that is not Excel format. You're making a tsv file (and corrupting data by removing line break characters). Use fputcsv and write straight to output, it will escape your data properly so you don't have to.
For your column selector, set an associative array with column names as keys and user-friendly labels as values. Use a form with checkboxes created from iterating the array, all with name="columns[]" and value set to column name and label echoed next to checkbox. in the part of the script reading the received values, first check if isset($_POST['columns']) and then if each value in the posted value array actually exists in your first array. If everything's okay, implode() the POSTed columns to use in your query.
Something to start you off, you don't have to use POST with a form that only reads data:
<?php
$columns = [
'device_name' => 'Device name',
'description' => 'Description',
...
];
// validate
if (isset($_GET['columns'])) {
if (!is_array($_GET['columns'])) {
unset($_GET['columns']);
}
else {
foreach ($_GET['columns'] as $k => $column) {
if (!is_string($column) || !isset($columns[$column])) {
unset($_GET['columns'][$k]);
}
}
if ($_GET['columns']) {
$_GET['columns'] = array_values($_GET['columns']);
}
else {
unset($_GET['columns']);
}
}
}
// no (valid) column selection
if (!isset($_GET['columns']) {?>
<form action="">
<?php foreach ($columns as $column => $label) {?>
<label><input type=checkbox value="<?php echo $column;?>">
<?php echo $label;?></label>
<?php }?>
...
<?php }
else {
...
$sql_ex = 'SELECT ' . implode(', ', $_GET['columns']) . ' FROM device';
...
// column headings
fputcsv($output, array_intersect_key($columns, array_flip($_GET['columns'])));
// output rows
...
}

printing last company in the excel file

I have done a program using PHPExcel and TCPDF on PHP. where I can select companies listed in excel file according to column that they are located.
I am tracking companies between already defined columns and between rows that I can scan till "next company's name". So that I can print them out in the screen.
I upload a screenshot how my excel file looks like...
after I retrieve the data from excel file it looks like
However, when I select last company since there is no "next company", it doesn't return result; on the contrary it gives an error.
my question: how can I control "last company" and print it out like the others. I couldn't put an exceptional condition for last one.
related part of my code looks like this:
if(isset($_POST['submit']))
{
$selected_val = $_POST['my_select']; // Storing Selected Value In Variable
$only_row = explode('.',$selected_val);
//echo "You have selected :" .$selected_val. "<br />"; // Displaying Selected Value
//echo "selected row value :".$only_row[1]. "<br />"; this shows selected company's row number
for($i=0; $i< $count; $i++)
{
if ($comp[$i][2]== $only_row[1])
{
$info_end=($comp[$i+1][2]-1);// here table ends before the next company's name begins
}
}
}
else{error_reporting(E_ALL ^ E_NOTICE);}
$rowCompanyInfoStart = $only_row[1]+2;
$rowCompanyInfoEnd = $info_end;
$colCompanyInfoStart = 'C';
$colCompanyInfoEnd = 'M';
PS: it would be appreciated if you can give a clear answer.
If something is unclear on the question, please let me know.
All you got to do is a test on $i, because you can't access $comp[$i+1][2]-1 when $i = $count-1.
So to do something different if this is the last line :
for($i=0; $i< $count; $i++) {
if ($comp[$i][2]== $only_row[1]) {
// line found
if($i == ($count - 1)) {
// what you want to do on last line...
} else {
// what to do normally
$info_end=($comp[$i+1][2]-1);
}
}
}
thanks to #Random
here is my full solution with exception for the last company
if(isset($_POST['submit']))
{
$selected_val = $_POST['my_select']; // Storing Selected Value In Variable
$only_row = explode('.',$selected_val);
//echo "You have selected :" .$selected_val. "<br />"; // Displaying Selected Value
//var_dump($only_row);
//echo "selected row value :".$only_row[1]. "<br />";
for($i=0; $i< $count; $i++) {
if ($comp[$i][2]== $only_row[1]) {
// line found
if($i == ($count - 1)) {
// what you want to do on last line...
$info_end=($objPHPExcel->setActiveSheetIndex(0)->getHighestRow());
}
else {
$info_end=($comp[$i+1][2]-1);
}
}
}
}

Make more than one database call in wordpress plugin (PHP CRUD)

I have 2 pieces of code from a simple plugin that work independently from each other but don't work together.
if(isset($_POST['submit'])){
if(has_presence($_POST['product_name'])){
insert_row_into_table('CAL_products');
show_errors();
if(has_presence($wpdb->last_query)) {
echo "Update Successful";
} else {
echo "Update Failed";
}
} else {
echo "The field 'Product Name' cannot be blank.";
}
}
And this one
$results_array = $wpdb->get_results("SELECT * FROM wpCMS_CAL_products ORDER BY id ASC");
echo build_table_from_results_array($results_array);
The functions are included at the bottom.
The problem I have is that when the page loads there is no $_POST so it skips over the if statement and builds the table. This table builds fine.
When the form is submitted the if statements come back true and the new value is added to the database successfully, but then the table doesn't build until the page is refreshed. If the code to build the table is put at the top above the if statement it builds fine but doesn't include the new value until the page is refreshed.
Is it possible to add a new item to the database table before the results are populated to the HTML table?
function insert_row_into_table($table_name){
global $wpdb;
$prefix = $wpdb->prefix; //Define the wordpress table prefix
$table = $prefix . $table_name; //Build the table name
unset($_POST['submit']);
echo print_r($_POST);
$data = $_POST; //collect the data from post
$wpdb->insert( $table, $data ); //insert data into the table
}
function show_errors(){
echo $wpdb->show_errors();
echo $wpdb->print_error();
}
function has_presence($value) {
return isset($value) && $value !== "";
}
function build_table_from_results_array($results_array) {
$out = "";
$out .= "<table class=\"widefat\">";
$out .= "<thead>";
foreach($results_array[0] as $key => $element) {
if($key == "id") {
$out .= "<th class=\"id-column\">";
$out .= strtoupper($key);
$out .= "</th>";
} else {
$out .= "<th>";
$out .= ucwords(str_replace("_", " ", $key));
$out .= "</th>";
}
}
$out .= "</thead>";
$out .= "<tbody>";
$i = 0;
foreach($results_array as $key => $element){
if($i % 2 === 0) $extraclass= "alternate";
$out .= "<tr class=\"$extraclass\">";
$i++;
$extraclass="";
foreach($element as $subkey => $subelement){
$out .= "<td>$subelement</td>";
}
$out .= "<td>EDIT</td>";
$out .= "</tr>";
}
$out .= "</tbody>";
$out .= "</table>";
return $out;
}
A general pattern for this type of page is Post-Redirect-Get. You could, for instance, pull the if(isset($_POST['submit'])) block out into a separate file called processForm.php. The form's action parameter is changed to processForm.php. The form sends $_POST data to processForm which inserts the new database records, and processForm in turn redirects the user back to the original page which gets the results.
If you want a one-page solution using the above code, add this code at the very top of the file, before you output anything at all. This starts the output buffer, which is usually necessary if you want to use the header() command to redirect.
ob_start();
Then edit the if(isset) block:
if(isset($_POST['submit'])){
if(has_presence($_POST['product_name'])){
insert_row_into_table('CAL_products');
show_errors();
if(has_presence($wpdb->last_query)) {
echo "Update Successful";
header("Location: index.php"); //change index.php to the current page
//header("Location: ".$from); //or use a variable
} else {
echo "Update Failed";
}
} else {
echo "The field 'Product Name' cannot be blank.";
}
}
Finally, add this at the very end of the script to close the output buffer:
ob_end_flush();
Essentially, this code refreshes the page on success after the new entries are inserted into the database. This should allow your table to include the new records.

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

How to split part of table into 2 columns over specific number of td's with PHP?

The site I'm working on wants data organized in a specific way. I need to split it into two columns if it's over 8 td's long. Here is my code right now. I've put it into an array as I had an idea about doing that and using the count to display data but I haven't figured out how to make that work.
$resultFound = false;
$prevWeek = -1;
$count = 0;
while($row = mysqli_fetch_array($result)) {
$adjustedWeek = dateToWeek($row['date']) - 35;
if($_GET['keywords'] != "") {
$id = search($row, $_GET['keywords']);
if($row['id'] == $id) {
if($validWeek) {
if($week == $adjustedWeek) {
include('test2.php');
}
}
else {
include('test2.php');
}
}
}
foreach($tableArray as $table) {
echo $table;
}
Here is my code for test2.php
$table = "";
if($prevWeek != $adjustedWeek) {
$table .= ('<th colspan=2>Week' . $adjustedWeek . '</th>');
$prevWeek = $adjustedWeek;
}
$table .= '<tr>';
$table .= ('<td colspan=12><a href="details.php?id=' . $row['id'] . '">'
. getGameTitleText($row) . '</a></td>');
$table .= '</tr>';
$resultFound = true;
$tableArray[] = $table;
$count++;
I need the code to do something like this:
If (all items of any week > 8)
write out 8 items to column one
then write the rest to column two
I've accounted for the total number of entries it's searching but not specific to a week, and I don't want to have to make lots of variables for that either to keep track.
How could I get the result like I want?
Warning!! the following code is to illustrate the idea only. Not tested on machine, but I think you can iron the possible error out.
pseudo code example:
$arr=array();
while($row = mysqli_fetch_array($result)) {
$arr[]['data']=$row['data'];
$arr[]['whatever']=$row['whatever'];
}
$columns=floor(count($arr)/8);
$output="<table>";
foreach ($arr as $i=>$a){
$output.="<tr>";
$output.="<td>{$arr[$i]['data']}</td>";
if ($columes>0){
for($j=0;$j<$columes;$j++){
$row_number=$i+($j+1)*8;
$output.="<td>{$arr[$row_number]['data']}</td>";
}
}
$output.="</tr>";
}
$output.="</table>";
This code will continue to add the third column if 2 is not enough.
You may still want to put a test for the end of array, so you don't get a bunch of warning when the $row_number is larger than count($arr)
This is how I ended up doing it. It's a bit "dirty" because it echo's out an extra /table and /tr at the beginning but it works for my purposes and is simpler than the code already posted. That was too complex for me
$table = "";
if($prevWeek != $adjustedWeek) {
$table .= '</tr></table><table class="vault_table">';
$table .= ('<tr><th>Week ' . $adjustedWeek . '</th></tr>');
$table .= '<table class="vault_table">';
$prevWeek = $adjustedWeek;
}
if($count % 2 == 0) {
$table .= '<tr>';
}
$table .= ('<td><a href="details.php?id=' . $row['id'] . '">'
. getGameTitleText($row) . '</a></td>');
$resultFound = true;
$tableArray[] = $table;
$count++;
The class is just for styling the table. Didn't have anything to do with how it's being layed out. other than each side of the table being 50% width of the container

Categories