gpt4 book ai didi

php - 使用 php/mysql 保存所有输入(没有 bindig 参数一个接一个)的正确方法是什么?

转载 作者:可可西里 更新时间:2023-11-01 08:04:06 25 4
gpt4 key购买 nike

假设我的 HTML 表单中有 50 个输入元素,我想将它们全部保存在一个表中,那么我是否应该为每个输入创建一个变量并将它们一一绑定(bind)并插入到我的表中?

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

最佳答案

无需显式绑定(bind)每个字段。您可以只提供包含所有值的数组作为 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 ) );

关于php - 使用 php/mysql 保存所有输入(没有 bindig 参数一个接一个)的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38567169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com