Jump to content


Photo

Loop thru field name and value


  • Please log in to reply
1 reply to this topic

#1 craygo

craygo
  • Staff Alumni
  • Advanced Member
  • 1,973 posts
  • LocationRhode Island

Posted 06 April 2006 - 01:42 AM

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

#2 craygo

craygo
  • Staff Alumni
  • Advanced Member
  • 1,973 posts
  • LocationRhode Island

Posted 06 April 2006 - 12:59 PM

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.

<?
// 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>';
?>

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

Ray




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users