Suppose I've a large form, 25 fields consisting of textboxes, radio buttons, checkboxes, select tags, textareas etc.
Once the form is submitted, what would be the best way to collect those values and then store them into database; by best practice I mean using as minimal lines of code as possible.
There is the traditional way:
$name = $_POST['name'];
$age = $_POST['age'];
$city = $_POST['city'];
which is definitely not the way to go.
There is then another way :
foreach($_POST['submit'] as $key=>$val)
{
$$key = $val;
}
but again this will require a huge INSERT SQL statement:
"INSERT INTO tablename (col1, col2, col3, col4,...col25)
VALUES('$var1', '$var2', '$var3',.....'$var25')"
Using foreach to capture values is good, but then it comes with an elongated SQL INSERT statement. I'm sure there must a better way to use the INSERT statement. Ideas, suggestions, critics are all welcome.
Thanks, Nisar
In HTML change as follows
<input type="text" name="pval[name]" value="test" />
<input type="city" name="pval[city]" value="Bangalore" />
Then in the server side
Updated :
// Need to have the predefined array which is having valid fields
$fields = array('name', 'city');
$pval = $_POST['pval'];
foreach( $pval as $field_name => $val ){
if( ! isset($fields[$field_name]) ){ // If it is not a valid field name
unset($pval[$field_name]);
}
}
if( count($pval) > 0 ){
$pval = array_map( 'mysql_real_escape_string', $pval );
//Then its easy to write the query as follows
$qry = "INSERT INTO table_name( ". implode( ',', array_keys( $pval ) ) .") values( '". implode( "','", $pval ) . "')";
}
You don't need that traditional way, you can use extract
function like:
extract($_POST);
This will make all indexes as variables with values.
In other way, to store in database, you can either serialize
values or store in JSON
format. And then store whole form values as single entry in DB (if there is nothing relational and purpose is only to store values.)