views:

41

answers:

2

Hi There! There is a problem of automatically retrieving field names from a MySQL table. If possible could the name be placed in this format along with the dynamically created text box? :

The codes that I have created so far are located below:

<?php

include "db_connect.php";

$name = mysql_query("SELECT * from users");

$property = mysql_fetch_field($name);

$i = 0;

$result = mysql_query("SHOW COLUMNS FROM users");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
    while($i<mysql_num_fields($result))
    {
      $meta=mysql_fetch_field($name,$i);
      $new = $meta->name;
      echo "$new: <input type=\"text\" name=\"{$row['Field']}\" size=\"40\"   
      maxlength=\"256\" /><br>";
      $i++;
    }
}
}
?>

The Dynamically created text box (according to the number of columns from the table) are working fine but the field names cannot be generated! Can someone please give advice or help on this? Thanks!

A: 

Answer:

<?php

include "db_connect.php";

$name = mysql_query("SELECT * from checkusers");

$property = mysql_fetch_field($name);

$result = mysql_query("SHOW COLUMNS FROM checkusers");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
    for ($i = 0; $i < mysql_num_fields($name); $i++)
    {
      $meta=mysql_field_name($name, $i);
      echo "$meta: <input type=\"text\" name=\"{$row['health_id']}\" size=\"40\" 
      maxlength=\"256\" /><br>";
    }

?>
JavaNoob
A: 

Code below will get table columns and generate the list of inputs. In you code you have a lot of things that are useless. You do not need to select * from users...

Here is the code

<?php
include "db_connect.php";

//  This is not needed! Useless query that loads all the info from db
//$name = mysql_query("SELECT * from users");
//$i = 0;


//  Here you are getting culumns information
$result = mysql_query("SHOW COLUMNS FROM users");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

//  Scan through all the fields
while ($field = mysql_fetch_object($result)) {

    //  structure of $field looks like this
    /*
      object(stdClass)[1]
      public 'Field' => string 'id' (length=2)
      public 'Type' => string 'int(11)' (length=7)
      public 'Null' => string 'NO' (length=2)
      public 'Key' => string 'PRI' (length=3)
      public 'Default' => null
      public 'Extra' => string 'auto_increment' (length=14)
     */

    //
    echo "$field->Field: <input type=\"text\" name=\"$field->Field\" size=\"40\" maxlength=\"256\" /><br>";
}
?>
Alex
Yup thanks dude your codes are neater and shorter!
JavaNoob