Skip to content

Instantly share code, notes, and snippets.

@aa21
Last active January 23, 2018 03:38
Show Gist options
  • Save aa21/a0da4f24fb42fbc8889f to your computer and use it in GitHub Desktop.
Save aa21/a0da4f24fb42fbc8889f to your computer and use it in GitHub Desktop.
Create table columns on the fly on a mysql db
<?php
$conn = mysqli_connect($ht, $ur, $pd);
mysqli_select_db($conn, $db);
//foreach req, check if the column exists, otherwise create it
foreach($_POST as $k => $v){
$key = trim(mysqli_real_escape_string($conn, $k));
$sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='$tb' AND COLUMN_NAME='".$key."'";
$result = mysqli_query($conn, $sql);
if( mysqli_num_rows($result) == 0){
$sql = "ALTER TABLE `$tb` ADD `".$key . "` text";
mysqli_query($conn, $sql);
}
$insert[$key] = trim(mysqli_real_escape_string($conn, $v));
}
//insert the req
i($conn,$tb,$insert );
function i($conn, $table, $array) {
$query = "INSERT INTO ".$table;
$fis = array();
$vas = array();
foreach($array as $field=>$val) {
$fis[] = "`$field`";
$vas[] = "'".$val."'";
}
$query .= " (".implode(", ", $fis).") VALUES (".implode(", ", $vas).")";
if (mysqli_query($conn, $query))
return mysqli_insert_id($conn);
else return false;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment