Looping Through Fields in A Row, Can it be done?

Discussion in 'PHP' started by abrown72, Dec 5, 2007.

  1. #1
    Hey All, I am fairly new to PhP but not coding, so I half ass know what i am doing, but only half :)

    I have been asked by my boss to create a PhP page that can have an SQL statement dropped into it then return the results with some nice formating.

    So the problem is I have no idea what the Select statement may be, they will be thought of over time, so the entire process must be dynamic.

    I know how to write the code to pull the row headers and loop through each row, but is there a way to loop through each field within a row to dynamically generate it?..

    Here is my code so far,

    echo "<table cellspacing='5' border=1>";
    echo "<tr><td colspan='5'align=center bgcolor=lightgrey>";
    echo "<b>$tableTitle</b>";
    echo "</td></tr>";
    echo "<tr>";
    for ($col=1; $col<=odbc_num_fields($result); $col++)
    {
    echo "<td bgcolor=whitesmoke>";
    echo "<b>";
    printf("%s\n", odbc_field_name($result, $col));
    echo "</b>";
    echo "</td>";
    }

    while (odbc_fetch_row($result))
    {
    $date=odbc_result($result,1);
    $qty=odbc_result($result,2);
    $model=odbc_result($result,3);
    $desc=odbc_result($result,4);
    $cost=odbc_result($result,5);

    echo "<tr>";
    echo "<td>$date</td>";
    echo "<td>$qty</td>";
    echo "<td>$model</td>";
    echo "<td>$desc</td>";
    echo "<td>$cost</td>";
    echo "</tr>";

    }
    echo "</table>";

    So I need to replace the BLUE text with another looping statement that can step through each unkown field within each row that is returned.

    Any help will do, thanks all!
     
    abrown72, Dec 5, 2007 IP
  2. tonybogs

    tonybogs Peon

    Messages:
    462
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Try something like this

    
    $num = odbc_num_rows($result);
    
    for($i=1; $row=odbc_fetch_array($result,$i); $i++)
    {
        echo '<tr>';
        foreach ($row as $fieldName => $fieldValue)
        {
            echo '<td>'.$fieldValue.'</td>';
            // You can also use the $fieldName if you need it
        }
        echo '</tr>';
    }
    
    PHP:
    I havent actually tested this for as im not on my development box this but it should work ok :)
     
    tonybogs, Dec 5, 2007 IP
  3. abrown72

    abrown72 Peon

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Worked perfect, that is exactly what I wanted.

    Thank you very much!
     
    abrown72, Dec 5, 2007 IP