If you spend a lot of time writing pages that take input from a form and insert it into a database, this function will save you time!
Please Note: You have to name your form fields the same as their corresponding table column is named in mysql for this to work.
<?php
function formToDB($table, $exceptions = '', $sql_type = 'insert', $sql_condition = NULL) {
$fields = '';
$values = '';
foreach ($_POST as $field => $value) {
if (!preg_match("/$field, /", $exceptions)) {
$value = mysql_real_escape_string($value);
if ($sql_type == 'insert') {
$fields .= "$field, ";
$values .= "'$value', ";
}
else {
$fields .= "$field = '$value', ";
}
}
}
$fields = preg_replace('/, $/', '', $fields);
$values = preg_replace('/, $/', '', $values);
if ($sql_type == 'insert') {
$sql = "INSERT INTO $table ($fields) VALUES ($values)";
}
elseif ($sql_type == 'update') {
if (!isset($sql_condition)) {
echo 'ERROR: You must enter a sql condition!';
exit;
}
$sql = "UPDATE $table SET $fields WHERE $sql_condition";
}
else {
echo 'ERROR: Invalid input for argument $sql_type: must be "insert" or "update"';
exit;
}
if (mysql_query($sql)) {
return true;
}
else {
return false;
}
} formToDB('users', 'submit, ');
formToDB('users', 'submit, userID, ', 'update', "userID = '".$_POST['userID']."'");
?>