This script will loop though all fields in a database and output the name and create a form field with appropriate record value.
This is useful if you don’t want to manually code the form, or don’t know all of the field names
// Assumes you have your database connected here using variable $conn
// Set a flag to determin if you're editing here by checking $_GET for example
$editing = true;
if ($editing) {
// Fetch the record to edit
$result = $conn->query("SELECT * FROM `$table` WHERE ID = $id");
$row = $result->fetch_assoc();
}
// Grab the column names for your table
$result = $conn->query("SHOW COLUMNS FROM `$table`");
$columns = $result->fetch_all(MYSQLI_ASSOC);
// Loop through each column and work out its name and type
// Then output the appropriate form field for the data type
foreach ($columns as $column): ?>
<?php
$fieldName = $column['Field'];
$fieldType = $column['Type'];
// Skip auto-increment fields (like 'id')
if ($fieldName == 'WebsiteID') continue;
$value = $editing && isset($row[$fieldName]) ? htmlspecialchars($row[$fieldName]) : '';
?>
<div class="WebsiteField">
<label for="<?php echo $fieldName; ?>">
<?php echo ucfirst(str_replace('_', ' ', $fieldName)); ?>
</label>
<?php if (strpos($fieldType, 'enum') !== false): ?>
<!-- Handle ENUM fields as dropdowns -->
<?php
preg_match("/^enum\('(.*)'\)$/", $fieldType, $matches);
$enumValues = explode("','", $matches[1]);
?>
<select name="<?php echo $fieldName; ?>" id="<?php echo $fieldName; ?>">
<?php foreach ($enumValues as $enumValue): ?>
<option value="<?php echo $enumValue; ?>" <?php echo ($value == $enumValue) ? 'selected' : ''; ?>>
<?php echo $enumValue; ?>
</option>
<?php endforeach; ?>
</select>
<?php elseif (strpos($fieldType, 'text') !== false): ?>
<textarea></textarea><br>
<?php else: ?>
<!-- Default to text input -->
<input type="text" name="<?php echo $fieldName; ?>" id="<?php echo $fieldName; ?>" value="<?php echo $value; ?>">
<?php endif; ?>
<div class="ClearFix"></div>
</div>
<?php
endforeach;
// Tidy Up The Connection
$conn->close();
Disclaimer: The code on this website is provided "as is" and comes with no warranty. The author of this website does not accept any responsibility for issues arising from the use of code on this website. Before making any significant changes, ensure you take a backup of all files and do not work directly on a live/production website without thoughly testing your changes first.