As the others have stated, there remains the possibility that a malicious user might edit the names of fields in the DOM, but that said the following might be of interest.
$sql='insert into `claims_motor` (`'.implode( '`,`', array_keys( $_POST ) ) .'`) values (:'.implode(',:',array_keys( $_POST ) ).');';
foreach( $_POST as $field => $value ) $params[":{$field}"]=$value;
$statement = $pdo->prepare( $sql );
$statement->execute( $params );
In answer to your question about removing spurious html from the input data, you could try something along the lines of the following:
$options=array( 'flags'=>FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_ENCODE_LOW | FILTER_FLAG_ENCODE_HIGH | FILTER_FLAG_ENCODE_AMP );
function filterfield( $field ){
global $options;
return ":".strip_tags( filter_var( $field, FILTER_SANITIZE_STRING, $options ) );
}
function filtervalue( $field ){
global $options;
return strip_tags( filter_input( INPUT_POST, $field, FILTER_SANITIZE_STRING, $options ) );
}
function isfield( &$field, $key, $fields ){
$field=in_array( $field, $fields ) ? $field : false;
}
$sql='insert into `claims_motor` (`'.implode( '`,`', array_keys( $_POST ) ) .'`) values (:'.implode(',:',array_keys( $_POST ) ).');';
foreach( $_POST as $field => $value ) $params[ filterfield( $field ) ]=filtervalue( $field );
I'm not suggesting this is a perfect solution but it more or less answers your original question. You can find out more about filters here
I tried this using PDO with an included DROP
statement in the value and that was OK - was inserted as string data. When I tried modifying a field name it cause a PDOException
and did nothing else....
To get the column names as you suggest you can try:-
$sql="select group_concat(`column_name`) as 'cols'
from `information_schema`.`columns`
where `table_schema`=database() and `table_name`=:table;";
$params=array(':table' => 'claims_motor');
$statement = $pdo->prepare( $sql );
$statement->execute( $params );
/* Process the recordset */
$cols=$rs->cols; /* or whatever method to access the record */
/* Filter fields that were not in form - if any */
$cols=explode( ',', $cols );
array_walk( $cols, 'isfield', array_keys( $_POST ) );
$fields = array_filter( $cols );
/* Prepare sql for the insert statment */
$sql_insert='insert into `claims_motor` (`'.implode( '`,`', $fields ) .'`) values (:'.implode( ',:', $fields ).');';
/* reset params array */
$params=array();
/* Construct new array of bound variables / params */
foreach( $_POST as $field => $value ) $params[ filterfield( $field ) ]=filtervalue( $field );
/* add the data to db */
$statement = $pdo->prepare( $sql );
$statement->execute( $params );