Search code examples
phpmysqlforeachfieldskip

PHP MySQL How to skip displaying a field


I have the table MYTABLE that contains the fields: ID, PASSWORD, COL1, COL2, COL3, DATE I would like to fetch and display all records in an html table but skipping ID and PASSWORD fields... I'm using the following code which isn't working:

$query = "SELECT * FROM MYTABLE WHERE 1";
$results = mysql_query($query, $conn) or die(mysql_error());
echo "<tr>";
while ($r = mysql_fetch_assoc($results)) {
    foreach ($r as $item) { 
        // let's not display ID and password
        if ($r == 'ID' || $r == 'PASSWORD') continue; // this is the line that I want to figure out 
    echo "<td>$item</td>";  
    } // end for loop
} // end while  
unset($item);
echo "</tr>";

Obviously there's more than 1 way to do it, for example I can replace the foreach loop with a for loop:

for ($i=0;$i<=6;$i++) {
    if ($i == 0 || $i == 1 ) continue;
    echo "<td>$r[$i]</td>";
} // end for

This will skip ID and PASSWORD fields but I don't want to use it, because I'm running the code on more than one table (table name is fetched from html select tag) and these tables may not have the same number of fields/columns (but they will always have ID and PASSWORD).

I can also do it with SQL statement (I don't want to), but then I'll have to query into a temp, drop the ID,PASSWORD columns and then fetch from the temp table. (by the way is there a compelling reason as to why I SHOULD in fact do it with SQL rathen than PHP?)


Solution

  • Try this:

    $query = "SELECT * FROM MYTABLE WHERE 1";
    $results = mysql_query($query, $conn) or die(mysql_error());
    echo "<tr>";
    while ($r = mysql_fetch_assoc($results)) {
        foreach ($r as $key => $item) { 
            // let's not display ID and password
            if (!in_array($key, array('PASSWORD', 'ID'))) {
                echo "<td>$item</td>";  
            }
        } // end for loop
    } // end while  
    echo "</tr>";