HashHazard
HashHazard

Reputation: 561

Dynamic Table Iteration PHP MySql

Suppose I have an SQL Statement that looks like:

SELECT * FROM myTable;

Now back in PHP I have a result array $result[], How can I iterate through that array and print out the values if I don't know the column names? Can I interrogate the array somehow?

Background: I have a table, I've rendered the table headings based on the a metadata table, now I need to populate the data, but I only want to pull out the field names that match the table headers and insert them into the HTML Table.

This process is happening dynamically, every table is different and has different field names (discovered by interrogating the metadata), but shares the same php code, so it needs to be flexible and smart enough to figure out what to render.

Upvotes: 1

Views: 194

Answers (2)

Bill Karwin
Bill Karwin

Reputation: 562611

Edit: I now understand that your $result is an array of arrays.

foreach ($result as $row) {
    foreach ($row as $key => $value) {
      print "column $key has value $value\n";
    }
}

Or you can call array_keys($row) to return the keys of an associative array.

Upvotes: 1

Snehal S
Snehal S

Reputation: 875

You can use foreach loop with key-value pair in that case.

You can use it like this,

foreach($result as $key=>$value) {
    //$key returns the key of $result array
    //$value returns the respective value of that key
}

Upvotes: 0

Related Questions