Jump to content

Loop thru field name and value


craygo

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
Link to comment
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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.