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!
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With