I built a function that should greatly simplify working with long HTML forms, that save data to MySQL using PHP.
My forms usually have several hundred input elements that are added / altered / removed frequently from the form.
Goal of this function is to only write frontend HTML form markup, MySQL structure gets updated automatically once form is submitted. If new form is not yet being stored into a table, table is automatically created.
<?php
$mysqli = mysqli_connect('127.0.0.1', 'root', '', 'test');
$mysqli->set_charset('utf8');
function SubmitForm($mysqli, $table) {
if(isset($_POST['submit'])) {
// unset redundant $_POST fields
unset($_POST['submit']);
// create table if not exists
$mysqli->query('create table if not exists `'.$table.'` (`id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, `status` INT(11) NOT NULL DEFAULT "1", `date_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `code` VARCHAR(100) NOT NULL, UNIQUE KEY `code_unique` (code)) ENGINE=MyISAM DEFAULT CHARSET=utf8') or die($mysqli->error);
// prepare data
$next_after = null; // used to add columns in order of $_POST fields
$columns = $placeholders = $types = $values = $duplicates = array();
foreach ($_POST as $key => $value) {
// add column if not exists
$column_query = $mysqli->query('show columns from `' . $table . '` like "'.$key.'"') or die($mysqli->error);
if ($column_query->num_rows === 0) {
$mysqli->query('alter table `' . $table . '` add `' . $key . '` text NOT NULL ' . $next_after) or die ($mysqli->error);
}
// set AFTER for next column check query
$next_after = 'after `' . $key . '`';
// implode arrays that are passed from select[multiple='multiple']
$value = is_array($value) ? implode(',', $value) : $value;
// prepare data for query
$columns[] = $key;
$placeholders[] = '?';
$types[] = 's';
$values[] = $value;
$duplicates[] = $key . ' = values(' . $key . ')';
}
// insert / update data
$stmt = $mysqli->prepare('insert into '.$table.' ('.implode(',', $columns).') values('.implode(',', $placeholders).') on duplicate key update '.implode(',', $duplicates)) or die($mysqli->error);
$stmt->bind_param(implode('', $types), ...$values);
$stmt->execute();
// return success
return 'form saved';
}
return null;
}
echo SubmitForm($mysqli, 'table_name');
?>
<form method="post">
<input type="text" name="code" value="<?php echo time(); ?>" />
<input type="text" name="apples" />
<input type="text" name="bananas" />
<input type="text" name="grapes" />
<input type="submit" name="submit" />
</form>