Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an HTML form depending on database fields [closed]

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!

like image 755
user2176205 Avatar asked Dec 26 '22 04:12

user2176205


2 Answers

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>
like image 51
Kevin Avatar answered Dec 27 '22 19:12

Kevin


Using Ghosts example including F3 and its template engine as requested

<?php

$f3 = require 'lib/base.php';

$db = new DB\SQL('mysql:host=localhost;dbname=DBNAME', 'USERNAME', 'PASSWORD');
$res = $db->exec('DESCRIBE `TBLUSERS`');

foreach($res as $row) {
    $fields[] = $row['Field'];
}

$f3->set('fields', $fields);

echo Template::instance()->render('form.html');

?>

<!-- form.html -->
<form id="generate-form" type="POST">
    <repeat group="{{@fields}}" value="{{@field}}">
        <label>
            {{@field}}:
            <input type="text" name="{{@field}}" />
        </label><br/>
    </repeat>
    <input type="submit" name="submit" />
</form>
like image 39
sascha Avatar answered Dec 27 '22 21:12

sascha