简体   繁体   中英

How to remove selected columns from dynamically generated html-table?

I have an SQL-database where I read out data that are then shown in a dynamically generated html-table. Here is my code that works fine:

$sql = "SELECT $selection FROM $tabelle WHERE $masterarray";


$result = mysqli_query($db, $sql) or die("Invalid query");             
$numrows = mysqli_num_rows($result);  
$numcols = mysqli_num_fields($result); 
$field = mysqli_fetch_fields($result); 


if ($numrows > 0) {

echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";


for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}

echo "</tr>";
echo "</thead>";

echo "<tbody>";
echo "<tr>";
$nr = 1;

while ($row = mysqli_fetch_array($result)) {
  echo "<td>" . $nr . "</td>";
  for ($k=0; $k<$numcols; $k++) {    
  echo "<td>" . $row[$k] . "</td>"; //Prints the data
  }

 $nr = $nr + 1;
 echo "</tr>";

 }
 echo "</tbody>";
 echo "</table>";

}
}

mysqli_close($db); 

Now, I want to remove specific columns (eg those, which are empty or those, which are not that interesting for the user, who makes the request).

I tried it with unset($field[$variable]) , however, it didn't work. In addition, the values (if there are any), should be removed, too.

Always format the array before you print it. Try to remove the specific columns from the $field array before you echo the HTML and then print the final table. Once the HTML code is echoed in PHP you won't be able to remove it without the use of JavaScript.

You can check against the $field[$x]->name variable and use continue to skip the column.

can let mysql filter them out for you, $sql = "SELECT $selection FROM $tabelle WHERE $masterarray AND LENGTH($selection) > 0";

-- http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_length

<?php

//  DataBase Config - http://php.net/manual/pt_BR/pdo.construct.php.
$dsn = 'mysql:host=localhost;dbname=test';
$usr = 'root';
$pwd = '';

try {   //  try to connect in database.

    $pdo = new PDO($dsn, $usr, $pwd);

} catch (PDOException $e) { //  if there is error in the connection.

    die('Connection failed: ' . $e->getMessage());

}

//  Prepare Statement and execute - http://php.net/manual/pt_BR/pdo.prepare.php.
$stm = $pdo->prepare('select id, weight, color, name from product');
$stm->execute();

//  Get ALL rows - Object.
$rows = $stm->fetchAll(PDO::FETCH_OBJ);

//  Print Rows.
//echo '<pre>'.print_r(rows, true).'</pre>';

//  Check $row;
if (count($rows)) {

    //  Order and Display Cols.
    $colsDisplay = [
        'id'        => 'ID Product',
        'name'      => 'Name',
        'weight'    => 'Weigth'
    ];

    //  Table.
    $html = '<table border="1">';
    $html .= "\n    <thead>";
    $html .= "\n        <tr>";
    $html .= "\n            <th  bgcolor='#eee'>Row</th>";
    $html .= "\n            <th>". implode("</th>\n         <th>", $colsDisplay) ."</th>";
    $html .= "\n        </tr>";
    $html .= "\n    </thead>";
    $html .= "\n    <tbody>";

    //  Loop ROWS.
    foreach ($rows as $key => $val) {

        $html .= "\n        <tr>";

        $html .= "\n            <td bgcolor='#eee'>". $key ."</td>";

        //  Loop COLS to display.
        foreach ($colsDisplay as $thKey => $thVal) {

            $html .= "\n            <td>". $val->$thKey ."</td>";

        }

        $html .= "\n        </tr>";

    }

    $html .= "\n".' </tbody>';
    $html .= "\n".'</table>';

    echo $html;

}

In order to know that a column is empty, you should check the whole column. There are different ways to do it, one of them could be investigating which of them are empty and then only using those that aren't empty. Something like this:

<?php
// ... 
$q = "SELECT SUM(LENGTH(my_first_column)) col_0, SUM(LENGTH(my_second_column)) col_1, ..., SUM(LENGTH(my_11th_column)) col_10 FROM $tabelle WHERE $masterarray";

// ... execute query and return results in $nonEmpty
$nonEmpty = array();
foreach($row as $columnIndex) {
  if ($row[$columnIndex] > 0) {
     $nonEmpty[] = $columnIndex;
  }
}
// ... now go through results and print only cols with at least one row with lenght > 0 i.e. non empty
$len = 11;
$rowHTML = "<tr>";
while ($row = mysqli_fetch_array($result)) {

   for ($i = 0; $i < $len; ++$i) {
      $rowHTML = '';
      if (!in_array($i, $nonEmpty)) {
         $rowHTML .= '<td>' . $row[$i] . '</td>';
      }
      $rowHTML .= "</tr>\n";
   }
}

// ...

This chunk of code will remove columns with ALL empty values. If you have at least one cell in the column with some value, you'll see the column in your result.

The code isn't optimized - it's just a rough idea. But it's a starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM