1

I'm working on a generic query viewer, and I have one last problem to solve.

Suppose I have a query that returns the following data...

|  Job Code  | Mon | Tue | Wed | Thu | Fri | Sat | Sun | 
--------------------------------------------------------
|  1234-567  |  0  |  3  |  2  |  5  |  2  |  0  |  0  |
|  3214-431  |  0  |  2  |  4  |  3  |  0  |  0  |  0  |

... and so on. When I run the code below, I get the following result in my browser. It looks like the associative array is being filled twice. I've seen this when I do the fetch array with MYSQLI_BOTH, but I should be getting just the associtive array with the code below.

|  Job Code  | Mon | Tue | Wed | Thu | Fri | Sat | Sun |   Job Code  | Mon | Tue | Wed | Thu | Fri | Sat | Sun | 
--------------------------------------------------------
|  1234-567  |  0  |  3  |  2  |  5  |  2  |  0  |  0  |
|  3214-431  |  0  |  2  |  4  |  3  |  0  |  0  |  0  |

Code...

function query2table( $dbcon, $query )
{
    // Connection is already made.
    $queryResult = mysqli_query($dbcon, $query);
    if( $queryResult )
    {
        echo "<TABLE cellpadding='5' cellspacing='1' border='1'><THEAD><TR>\n";
        while ($hdrrow = mysqli_fetch_assoc($queryResult) )
        {
            foreach ($hdrrow as $hdr => $value) {
                echo "<th>";
                echo $hdr;
                echo "</th>";
            }
        }
        echo "</TR></THEAD>\n";
        mysqli_data_seek($queryResult, 0);
        while ($row = mysqli_fetch_assoc($queryResult,MYSQLI_NUM))
        {
            foreach( $row as $cell )
            {
                echo "<TD>$cell</TD>";
            }

            echo "    </TR>\n";
        }
        echo "</TABLE>\n";

    } else {
        $error = mysqli_error($dbcon);
        echo "\n<BR><BR>dbi_displayQuery - Error reading database: $error<BR><BR>\n";
    }
}

Ideas?

1 Answer 1

1

You are looping through all your rows and outputting the header row as many times as you have results:

while ($hdrrow = mysqli_fetch_assoc($queryResult) )

For the header row, you just need to fetch one row and use that:

if ($hdrrow = mysqli_fetch_assoc($queryResult) )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.