用php/mysql保存所有输入(不带bindig params)的正确方法是什么


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

考虑到我的HTML表单中有50个输入元素,我想将它们全部保存在一个表中,那么我应该为每个输入创建一个变量,并将它们逐一绑定并插入到我的表中吗?

$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();

无需显式绑定每个字段。您只需为数组提供所有值作为execute()函数的参数。

// 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 ) );

你可以这样做:

foreach ($_POST as $key => $value) {
    $statement->bindParam(":".$key,$value);
}
$statement->execute();

如果您的表单有好的字段

使用$statement->execute(array('param1'=>$param1, 'param2'=>$param2))