Jump to content

Archived

This topic is now archived and is closed to further replies.

craygo

Loop thru field name and value

Recommended Posts

I have a table with about 40 fields What I want to do is loop thru the field names and values and print them to the screen to edit them.

So i have a row with id#2, I want to return each field name and the value for that field name in a loop.

Ray

Share this post


Link to post
Share on other sites
I figured it out.

If anyone is interested in retrieving all fields with the field names and their values for a respective row, so it can be edited without having to create an entire form. Here is what I used.

[code]<?
// make database connection here


$id = $_GET['id'];
// Print out headers and table
print '<form name=edit method=POST action=edit.php>
      <table width=600 align=center>
      <tr>
      <td width=200>Field Name</td>
      <td width=400>Value</td>
      </tr>';
// Run query
$sql = "SELECT * FROM table WHERE id = '$id'";
  $res = mysql_query($sql) or die(mysql_error());
// Start count for fields and row offsets
$i = 0;
// Get row data
      $r = mysql_fetch_row($res);
// Get field names
      while($i < mysql_num_fields($res)){
// Assign alias to field data
            $meta = mysql_fetch_field($res, $i);
// Print data in form
     print '<tr>
           <td>'.$meta->name.'</td>
           <td><input type=text name="'.$meta->name.'" value="'.$r[$i].'"></td>
           </tr>';
           $i++;
           }
// Print out final row with submit button
     print '<tr>
            <td colspan=2 align=center><input type=submit value=Change></td>
            </tr></table></form>';
?>[/code]

If someone has a simpler way of doing this, Please let me know.

Ray

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.