3

I am trying to execute a table from a MySQL database using a for loop statement, in order to get the field names as the column header.

Here is my code:

$result = mysql_query("SELECT * FROM bom_commonmaterials where description like '%CAP%'");
        if (!$result) {
            die("Query to show fields from table failed");
        }

        $fields_num = mysql_num_fields($result);

        echo "<table class ='tableinventory' id ='tabletoexcel'><thead><tr>";
        // printing table headers
        for($i=0; $i<$fields_num; $i++)
        {
            $field = mysql_fetch_field($result);
            echo "<th>{$field->name}</th>";
            if ($field ="WATTAGE")
            {
                CONTINUE;
            }
        }
        echo "</tr></thead>\n";
        // printing table rows
        while($row = mysql_fetch_row($result))
        {
            echo "<tr>";

            // $row is array... foreach( .. ) puts every element
            // of $row to $cell variable
            foreach($row as $cell)
                echo "<td>$cell</td>";

            echo "</tr>\n";

        }
        mysql_free_result($result);
        echo "</table>";

As you can see, I have an if statement $field ="WATTAGE" inside the for loop statement. I am trying to execute this code so that the field name WATTAGE will be not included as a table header, but I think my code is wrong.

In this case I need help on how to skip a specific field name, and also the field rows of this field name.

Note: I used loop statement in this because the table field name from the database is not fixed. For example the user wants to add new columns. So I can't just code it manually because the table doesn't have a fixed data.

4

You should have an IF ELSE in your for loop:

for($i=0; $i<$fields_num; $i++)

You are assigning $field to the string WATTAGE here:

$field = mysql_fetch_field($result);
echo "<th>{$field->name}</th>";

before you get to the code

echo "<th>{$field->name}</th>";
if ($field ="WATTAGE")
{
  CONTINUE;
}

WATTAGE has has already been assigned to $field before you get to if($field = "WATTAGE") code.

Put an IF/ELSE in your for loop and then put the CONTINUE; bit in the IF and the assignment in the ELSE part. That way you'll never get to the $field assignment if the fieldname is WATTAGE.

1
  • Then maybe you could mark my answer as correct? :-) – Vérace Jul 10 '15 at 3:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.