<html>
<!--
================================================================================================
== This PHP scripts takes data from an html form, and insert the data in a table
== The form must provide a hidden field called _table with a name
== The database table must have column names that are the same as the incoming field names
================================================================================================
-->
<head>
<title>Process an HTML form</title>
</head>
<body>
<?php include "../include.php"; ?> <!-- hyperlink to see the code -->
<?php
error_reporting(0);
//----- Retrieve form elements ---------------------------------------------
if ($_SERVER['REQUEST_METHOD'] == 'GET') //if method used is GET
$data = $_GET; //retrieve from $_GET array
else //otherwise
$data = $_POST; //retrieve from $_POST array
//----- Write data into Database ---------------------------------------------
$host = 'localhost';
$DBname = 'demo2';
$DBuser = 'demo2';
$DBpswd = 'demo2';
print '<br>';
$connect = mysqli_connect($host,$DBuser,$DBpswd,$DBname); #connect to db server
if (! $connect)
die('Could not connect: ' . mysqli_connect_error());
$colNames = '';
$colValues = '';
foreach($data as $fieldName => $fieldValue) #for each incoming field
{
if (is_array($fieldValue)) #if value is an array (eg. checkbox, select list)
$fieldValue = implode(',' , $fieldValue); #make it a string, comma delimited
if ($fieldName == '_table')
$tableName = $fieldValue; #the table name
else
{
$colNames .= $fieldName ."," ; #all column names, comma delimited
$colValues .= "'". $fieldValue ."'," ; #all column values, quoted & comma delimited
}
}
if (! $tableName)
die("<b>Must have a table name. See genericInsert.html</b>");
$colNames = preg_replace('/,$/', '', $colNames); #get rid of last ,
$colValues = preg_replace('/,$/', '', $colValues); #get rid of last ,
$insert = "INSERT INTO $tableName
($colNames)
VALUES($colValues)";
//print $insert; #for debugging
$result = mysqli_query($connect,$insert); #issue the query
if (! $result)
die('Could not execute update: ' . mysqli_error($connect));
mysqli_close($connect); #close connection
print "<b>Order Processed Successfully!!!</b>";
//=============================================================================
?>
<br><br>
</body>
</html>