Search code examples
phpjqueryhtmlmysqlfat-free-framework

Creating an HTML form depending on database fields


I am trying to create a program that will read the structure of a database table and generate a simple HTML registration form depending on it. Like if the table looks like this:

TBLUSERS
- Name (varchar)
- Age (int)
- Birthday (date)

Then it would output a form like this:

<form id="generated-form">
   Name: <input type="text" id="name"><br>
   Age: <input type="text" id="age"><br>
   Birthday: <input type="date" id="birthday"><br>
   <input type="submit">
</form>

But I don't know where to start. I prefer using anything that includes anything from Fatfree Framework since most of the project is done using it. Aside from this, I am only supposed to use HTML, JQuery, PHP and/or Javascript.

Any advices? Thanks in advance!


Solution

  • The first step of course is to obtain the table's column information thru the use of DESCRIBE.

    And then, you can just query it like any normal query, using mysqli in this case.

    Example:

    <?php
    
    $db = new mysqli('localhost', 'username', 'password', 'database');
    $query = $db->query('DESCRIBE `TBLUSERS`');
    $fields = array();
    while($row = $query->fetch_assoc()) {
        $fields[] = $row['Field'];
    }
    
    ?>
    
    <form id="generate-form" type="POST">
        <?php foreach($fields as $field): ?>
            <label>
                <?php echo "$field: "; ?>
                <input type="text" name="<?php echo $field; ?>" />
            </label><br/>
        <?php endforeach; ?>
        <input type="submit" name="submit" />
    </form>