I have a PHP script that generates an HTML table from a CSV file.
Right now if any cells are missing information, it skips the row. HOWEVER, I'd prefer if it skipped a row if more than one cell was missing. So if a row has 2 empty cells, it should skip.
I have marked it //edit here below but unsure how to acheive this.
<?php
$idsColumnsWanted = array(0,1,8,19);
echo "<table class='table table-bordered' id='example'>\n\n";
$f = fopen("users.csv", "r");
$first_line = false;
while (($line = fgetcsv($f)) !== false) {
// Restart column index
$i = 0;
$row ="";
if($first_line == false) {
$row = "<thead><tr>";
$col = "th";
} else {
$row = "<tr>";
$col= "td";
}
$is_empty = false;
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (! in_array($i, $idsColumnsWanted)) continue;
// edit here
if ($cell !== '') {
$row .= "<".$col.">" . htmlspecialchars($cell) . " </".$col.">";
} else {
$is_empty = true;
}
// Increase index
$i++;
}
if($first_line == false)
$row .= "</tr></thead>";
else
$row .= "</tr>";
$first_line = true;
if ($is_empty) {
continue;
} else {
echo $row;
}
}
fclose($f);
echo "\n</table>";
?>
please try this code
$is_empty = false;
$count = 0;
$countlimit = 2; // define empty cell limit here
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (!in_array($i, $idsColumnsWanted))
continue;
// edit here
if($cell==""){
$count++;
}
if ($count <= $countlimit) {
$row .= "<" . $col . ">" . htmlspecialchars($cell) . " </" . $col . ">";
} else {
$is_empty = true;
break;
}
}
You have to cound how many cells are empty in a row. To do so init the counter for each line.
$empty_cells = 0; //Init with 0 for each line
foreach ($line as $i => $cell) {
// Skips all columns not in your list
if (! in_array($i, $idsColumnsWanted)) continue;
// edit here
if ($cell !== '') {
$row .= "<".$col.">" . htmlspecialchars($cell) . " </".$col.">";
} else {
$empty_cells++; //count how many empty cells you have.
}
// Increase index
$i++;
}
and after that check if there are more than two empty cells like this:
if ($empty_cells >= 2) {
continue;
} else {
echo $row;
}
Related
I need to create a table whose first column is populated from subdirectory names inside a directory and rest are from a CSV file. This have to be a dynamic table and table headers have to be added from the code. What's wrong with my code?
I am an absolute beginner. So, please ignore my stupidity.
$dir = 'D:\workspace';
$dirlist = preg_grep('/^([^.])/', scandir($dir));
$row = 1;
if (($handle = fopen("D:\workspace\demo\database.csv", "r")) !== FALSE) {
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
foreach ($dirlist as $rowdirectory)
{
echo '<td>' . $rowdirectory . '</td>';
echo '<td>'.$value.'</td>';
}
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
<?php
#------------------------------------------Function for Reading Directory-------------------------------------------
function readdirectory($dir)
{
$dirlist = preg_grep('/^([^.])/', scandir($dir)); // for all(./../anything that
starts with .)
//$dirlist = preg_grep('/[^.]/', scandir($dir)); //only . & ..
//$dirlist =preg_grep('/^[(^.)]/', scandir($dir));//only files that starts with .
return $dirlist;
}
#------------------------------------------Function for Reading CSV file-------------------------------------------
function readcsvfile($source)
{
$handle = fopen($source, "r");
$filecontent = null;
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
$filecontent[] = $data;
}
fclose($handle);
return $filecontent;
}
$filecontent= readcsvfile("D:\workspace\demo\database2.csv");
#-------------------Directory Function calling, header array cration and other declaration------------------------------------
$conf_prefix= "../";
$conf_suffix="index.php";
$headerarray= $filecontent[0];
#var_dump($headerarray);
$headersize= count($headerarray);
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
$dir = 'D:\workspace';
$dirlist= readdirectory($dir);
#------------------------------------------Creating 1st row/Header row of Table-------------------------------------------
echo '<tr>';
for($a=0; $a<$headersize;$a++)
{
echo '<td>'.$headerarray[$a].'</td>';
}
echo '</tr>';
#-----------------------------Creating Table elements by comparing both directory arrays and CSV file array-------------------------------------------
foreach ($dirlist as $rowdirectory)
{
foreach ($filecontent as $value) {
$num = count($value);
if ($rowdirectory== $value[0])
{
$link= $conf_prefix. $rowdirectory."/".$conf_suffix;
echo '<tr>';
echo '<td> ' . $rowdirectory . ' </td>';
for( $c=1; $c < $num; $c++) {// loop for csv file
{
echo '<td>'.$value[$c].'</td>';//else print "value"
}
}
echo '</tr>';
}
}
}
?>
A few months ago, I made a system where people could upload a picture and then those pictures would be displayed in a table with 4 columns.
Now I am working on a project (to practice my php, I am still learning it) and I would like to use a similar system as below but it should display data from a database.
The result I was trying to achieve is the data being displayed in 2 columns.
if ($handle = opendir('images/')) {
$bool = true;
while ($bool) {
$td = 1;
echo '<tr>';
while ($td < 4) {
$file = readdir($handle);
if ($file != '.' && $file != '..' && $file != '.DS_Store') {
echo '<td>';
if ($file) {
echo '<img src="images/'.$file.
'">';
} else {
$bool = false;
}
echo '</td>';
$td++;
}
}
echo '</tr>';
}
}
closedir($handle);
For anyone looking for the answer:
$query = "SELECT * FROM webshop";
if($query_run = mysql_query($query)) {
$bool = true;
echo '<table>';
while($bool) {
$td = 0;
echo '<tr>';
while($td < 2) {
if($fetch = mysql_fetch_assoc($query_run)) {
echo '<td>';
$title = $fetch['title'];
$info = $fetch['info'];
/* Commented out for now, will be implemented later
$image = $fetch['image'];
$price = $fetch['price'];
*/
echo $title;
} else {
$bool = false;
}
echo '</td>';
$td++;
}
echo '</tr>';
}
echo '</table>';
}
I have the following script to display files inside a directory
<?PHP
# The current directory
$directory = dir("./");
# If you want to turn on Extension Filter, then uncomment this:
$allowed_ext = array(".deb", ".ext", ".ext", ".ext", ".ext", ".ext");
$do_link = TRUE;
$sort_what = 0; //0- by name; 1 - by size; 2 - by date
$sort_how = 0; //0 - ASCENDING; 1 - DESCENDING
# # #
function dir_list($dir){
$i=0;
$dl = array();
if ($hd = opendir($dir)) {
while ($sz = readdir($hd)) {
if (preg_match("/^\./",$sz)==0) $dl[] = $sz;$i.=1;
}
closedir($hd);
}
asort($dl);
return $dl;
}
if ($sort_how == 0) {
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return -1;
else return 1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return -1;
else return 1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return -1;
else return 1;
}
}else{
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return 1;
else return -1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return 1;
else return -1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return 1;
else return -1;
}
}
##################################################
# Getting The information
##################################################
$i = 0;
while($file=$directory->read()) {
$file = strtolower($file);
$ext = strrchr($file, '.');
if (isset($allowed_ext) && (!in_array($ext,$allowed_ext)))
{
// dump
}
else {
$temp_info = stat($file);
$new_array[$i][0] = $file;
$new_array[$i][1] = $temp_info[7];
$new_array[$i][2] = $temp_info[9];
$new_array[$i][3] = date("F d, Y", $new_array[$i][2]);
$i = $i + 1;
}
}
$directory->close();
##################################################
# Sorting the information
#################################################
switch ($sort_what) {
case 0:
usort($new_array, "compare0");
break;
case 1:
usort($new_array, "compare1");
break;
case 2:
usort($new_array, "compare2");
break;
}
###############################################################
# Displaying the information
###############################################################
$i2 = count($new_array);
$i = 0;
echo "<table class='CSSTableGenerator'>
<tr>
<td width=290>File name (Download)</td>
<td align=center width=70>Downloads</td>
<td align=center width=70>Depiction</td>
<td align=center width=50>Size</td>
<td align=center width=85>Modified</td>
</tr>";
for ($i=0;$i<$i2;$i++) {
if (!$do_link) {
$line = "<tr><td>" . $new_array[$i][0];
$line .= '</td><td>Depiction</td>';
$line .= "<td>" . number_format(($new_array[$i][1]/1024)) . " KB</td>";
$line .= "<td>" . $new_array[$i][3] . "</td></tr>";
}else{
$line = '<tr><td align=left ><A class="ex1" HREF="' .
$new_array[$i][0] . '">' .
$new_array[$i][0] .
"</A></td>";
$line .= '<td> </td>';
$line .= '<td>Depiction</td>';
$line .= "<td>" . number_format(($new_array[$i][1]/1024)) . " KB</td>";
$line .= "<td>" . $new_array[$i][3] . "</td></tr>";
}
echo $line;
}
echo "</table>";
?>
The output looks like that:
I am trying to fill the downloads column by getting the download counts of each file from mysql table
So i am facing 2 issues here:
How to get the stats using the array of the files $new_array[$i][0]
How can i then add this mysql query output inside $line .= '<td> </td>';
I have tried getting the stats from the table using this:
include("../config.php");
$query = "SELECT stats FROM download WHERE filename='$new_array[$i][0]'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$line .= '<td>' . $row['stats'] . '</td>';
}
but it didn't work, i think the issue is with the array $new_array[$i][0] because i tried writing a filename filename='com.name.app3_2.2-1_iphoneos-arm.deb' and i got the stats of this file
In your "getting the information part", you must initialise your arrays thusly:
##################################################
# Getting The information
##################################################
$i = 0;
$new_array = array();
while($file=$directory->read()) {
$file = strtolower($file);
$ext = strrchr($file, '.');
if (isset($allowed_ext) && (!in_array($ext,$allowed_ext)))
{
// dump
}
else {
$new_array[$i] = array();
$temp_info = stat($file);
$new_array[$i][0] = $file;
$new_array[$i][1] = $temp_info[7];
$new_array[$i][2] = $temp_info[9];
$new_array[$i][3] = date("F d, Y", $new_array[$i][2]);
$i = $i + 1;
}
}
$directory->close();
##################################################
In addition, I have noted that your line:
$query = "SELECT stats FROM download WHERE filename='$new_array[$i][0]'";
Would cause $query to be equal to:
SELECT stats FROM download WHERE filename='Array[0]'
When $i is 0.
What you should do is use the mysqli library thusly:
$mysqli = new mysqli("example.com", "user", "password", "database");
$query = "SELECT stats FROM download WHERE filename=?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $new_array[$i][0]);
$stmt->execute();
$stmt->bind_result($stats);//stats turns into a reference by default.
while($stmt->fetch()) { //$stats now contains the stats
$line .= '<td>'. htmlentities($stats).'</td>';
}
To deal with the problem of missing cells you just described, you might try:
$mysqli = new mysqli("example.com", "user", "password", "database");
$query = "SELECT stats FROM download WHERE filename=?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $new_array[$i][0]);
$stmt->execute();
$stmt->bind_result($stats);//stats turns into a reference by default.
$fetched = false;
while($stmt->fetch()) { //$stats now contains the stats
$line .= '<td>'. htmlentities($stats).'</td>';
$fetched = true;
}
if(!$fetched) {
$line .= '<td></td>'
}
I'm very new to php but have been experimenting fairly successfully with using 'fgetcsv' to bring in a CSV file and convert it into an html table.
However I also have a large CSV file with 70 columns and 700 rows, but I only want to display columns 1 to 47 and rows 3 to 21 in one table, and then same columns but rows 22 to 44 in another table.
I'd appreciate some help with this, below is the code I am currently using:
<?php
$row = 1;
if (($handle = fopen("CSV/test.csv", "r")) !== FALSE) {
echo '<table border="1">';
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
?>
<?php
$row = 1;
if(($handle = fopen("CSV/test.csv", "r")) !== false) {
$table1 = $table2 = '<table border="1">';
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$table1Add = $table2Add = false;
if($row >=3 && $row <= 21)
$table1Add = true;
if($row >=22 && $row <= 44)
$table2Add = true;
$num = count($data);
if($row == 1) {
$table1 .= '<thead><tr>';
$table2 .= '<thead><tr>';
for($c = 1; $c <= 47; $c++) {
$value = empty($data[$c]) ? " " : $data[$c];
$table1 .= '<th>'.$value.'</th>';
$table2 .= '<th>'.$value.'</th>';
}
$table1 .= '</tr></thead><tbody>';
$table2 .= '</tr></thead><tbody>';
} else {
if($table1Add) $table1 .= '<tr>';
if($table2Add) $table2 .= '<tr>';
for($c = 1; $c <= 47; $c++) {
$value = empty($data[$c]) ? " " : $data[$c];
if($table1Add) $table1 .= '<td>'.$value.'</td>';
if($table2Add) $table2 .= '<td>'.$value.'</td>';
}
if($table1Add) $table1 .= '</tr>';
if($table2Add) $table2 .= '</tr>';
}
$row++;
}
$table1 .= '</tbody></table>';
$table2 .= '</tbody></table>';
fclose($handle);
echo $table1;
echo $table2;
}
?>
for the columns try this
for ($c=0; $c < 47; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
So you print cells between column 0 and column 47.
For the row you have to set a a counter, and, inside the while statement, use an if to print the rows in the range that you need. It's better that you set an exit condition in while to exit after row 44 if you dont need the others.
I've got a table that is default sorted ascendingly by its 2nd column by numeric value.
I'm trying to grab the top 5 rows from this table, but my script doesn't seem to want to follow the tablesorter forced sort order I have, it's just taking the default non sorted data.
So how do I get my script to grab the sorted table data? I don't want to have to grab all the data and sort it again for this script.
here is my code
<?php
include("bestbrokers_array.php");
require('simple_html_dom.php');
$table = array();
$html = file_get_html('http://www.forexfbi.com/best-forex-brokers-comparison/');
$num=1;
foreach($html->find('tr') as $row) {
if($num <= 6)
{
$rating = $row->find('td',1)->innertext;
$name = $row->find('td',0)->plaintext;
$table[$name][$rating] = true;
$num++;
}
}
html_show_array($table);
?>
and..
<?php
function do_offset($level){
$offset = ""; // offset for subarry
for ($i=1; $i<$level;$i++){
$offset = $offset . "<td></td>";
}
return $offset;
}
function show_array($array, $level, $sub){
if (is_array($array) == 1){ // check if input is an array
foreach($array as $key_val => $value) {
$offset = "";
if (is_array($value) == 1){ // array is multidimensional
echo "<tr>";
$offset = do_offset($level);
echo $offset . "<td>" . $key_val . "</td>";
show_array($value, $level+1, 1);
}
else{ // (sub)array is not multidim
if ($sub != 1){ // first entry for subarray
echo "<tr nosub>";
$offset = do_offset($level);
}
$sub = 0;
echo $offset . "<td main ".$sub." width=\"120\">" . $key_val .
"</td>";
echo "</tr>\n";
}
} //foreach $array
}
else{ // argument $array is not an array
return;
}
}
function html_show_array($array){
echo "<table cellspacing=\"0\" border=\"2\">\n";
show_array($array, 1, 0);
echo "</table>\n";
}
?>