【发布时间】:2017-01-06 15:44:06
【问题描述】:
我目前有一个名为 fields 的关联数组,用于存储我的 HTML 输入字段中的所有 $_POST 变量。当我尝试将我的值绑定到 mySQL 数据库时使用关联数组变量。同样,我也使用相同的名称作为 mySQL 数据库的列标题。所以这是非常乏味和冗长的。有没有办法遍历列并为关联数组分配另一个循环的值?请检查下面的示例,并提前感谢您的帮助。
try {
$insertSql = "INSERT INTO tableExample";
$sqlCols = " (
a,
b,
c,
d,
e,
f,
g,
h,
i,
j,
k,
l,
m,
n,
o,
p,
q,
r,
s,
t,
u,
v,
w,
x
)";
$result = $db->prepare($insertSql . $sqlCols . " VALUES (
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?)");
$result->bindValue(1,$fields['a'],PDO::PARAM_STR);
$result->bindValue(2,$fields['b'],PDO::PARAM_STR);
$result->bindValue(3,$fields['c'],PDO::PARAM_STR);
$result->bindValue(4,$fields['d'],PDO::PARAM_STR);
$result->bindValue(5,$fields['e'],PDO::PARAM_STR);
$result->bindValue(6,$fields['f'],PDO::PARAM_STR);
$result->bindValue(7,$fields['g'],PDO::PARAM_STR);
$result->bindValue(8,$fields['h'],PDO::PARAM_STR);
$result->bindValue(9,$fields['i'],PDO::PARAM_STR);
$result->bindValue(10,$fields['j'],PDO::PARAM_STR);
$result->bindValue(11,$fields['k'],PDO::PARAM_STR);
$result->bindValue(12,$fields['l'],PDO::PARAM_STR);
$result->bindValue(13,$fields['m'],PDO::PARAM_STR);
$result->bindValue(14,$fields['n'],PDO::PARAM_STR);
$result->bindValue(15,$fields['o'],PDO::PARAM_STR);
$result->bindValue(16,$fields['p'],PDO::PARAM_STR);
$result->bindValue(17,$fields['q'],PDO::PARAM_STR);
$result->bindValue(18,$fields['r'],PDO::PARAM_STR);
$result->bindValue(19,$fields['s'],PDO::PARAM_STR);
$result->bindValue(20,$fields['t'],PDO::PARAM_STR);
$result->bindValue(21,$fields['u'],PDO::PARAM_STR);
$result->bindValue(22,$fields['v'],PDO::PARAM_STR);
$result->bindValue(23,$fields['w'],PDO::PARAM_STR);
$result->bindValue(24,$fields['x'],PDO::PARAM_STR);
$result->execute();
} catch (Exception $e) {
echo "Unable to store data";
echo $e->getMessage();
exit;
}
【问题讨论】:
-
您始终可以使用映射绑定字段名称和值索引,例如 $fields['a']=1; $fields['b']=2;或简写为 $fields=['a'=>1, 'b'=>2];。然后只需迭代这些字段并做你的事情。不是最优雅的解决方案,但就足够了:)。 PD:post 字段和数据库列的名称相同是不安全的,因为它基本上暴露了您的数据库结构!。