考虑到我的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();
答案 0 :(得分:2)
无需明确绑定每个字段。您可以只为数组提供所有值作为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 ) );
答案 1 :(得分:1)
你可以这样做:
foreach ($_POST as $key => $value) {
$statement->bindParam(":".$key,$value);
}
$statement->execute();
如果您的表单包含好字段
答案 2 :(得分:0)
使用$statement->execute(array('param1'=>$param1, 'param2'=>$param2))