Amin Amin - 4 months ago 7
SQL Question

what is the proper way to save all inputs(without bindig params one by one) with php/mysql?

Consider that i have 50 input elements in my HTML form, and i want to save them all in a table, so should i create a variable for each input and bind them one by one and insert it into my table?

$statement->bindParam(':var1',$name1);
$statement->bindParam(':var2',$address);
$statement->bindParam(':var3',$city);
$statement->bindParam(':var4',$state);
$statement->bindParam(':var5',$zip_code);
$statement->bindParam(':var6',$telephone);
$statement->bindParam(':var7',$email);
$statement->bindParam(':var8',$fiance);
$statement->bindParam(':var9',$wedding_date);
$statement->bindParam(':var10',$number_of_guest);
$statement->bindParam(':var11',$radio);
$statement->bindParam(':var12',$newspaper);
// and 13, 14, 15 ...
$statement->execute();

Answer

No need to bind every field explicitly. You can just provide the array with all values as a parameter to the execute() function.

// create the list of the column names from the $_POST keys
$keys = array_keys( $_POST );
// quote keys to prevent SQL injections, then remove surrounding quotes and add ` instead.
foreach ( $keys as $i => $key ) {
    $keys[$i] = '`' . trim( $PDO->quote( $key ), "'" ) . '`';
}
// results in: `var1`,`var2`,`var3`,etc...
$keys = implode( ",", $keys );
// create the list of the placeholders
// results in: ?,?,?,...
$placeholders = implode( ",", array_fill( 0, sizeof( $keys ), "?" ) );
// prepare the statement
// results in: INSERT INTO `table` (`var1`,`var2`,`var3`,etc...) VALUES (?,?,?,...)
$stmt = $PDO->prepare( "INSERT INTO `table` ($keys) VALUES ($placeholders)" );
// execute the statement with the values from the $_POST array
$stmt->execute( array_values( $_POST ) );
Comments