我想将数组值写入我的数据库,如:
“UPDATE tbl SET $ fieldname = $ fieldvalue WHERE id = $ recid”
我从$_POST['changed']
得到了这个数组:
[changed] => Array
(
[0] => Array
(
[recid] => 1
[vorname] => Walter
[nachname] => Bauer
)
[1] => Array
(
[recid] => 2
[vorname] => Michael
)
[2] => Array
(
[recid] => 3
[vorname] => Peter
[nachname] => Highler
[email] => p.highler@aol.com
)
[3] => Array
(
[recid] => 4
[vorname] => Maria
[nachname] => Maier
)
[4] => Array
(
[recid] => 5
[vorname] => Werner
[nachname] => Rock
)
)
当我使用此foreach
循环执行此操作时,recid
获取也作为字段名称 - 但这不应该发生。
foreach ($_POST['changed'] as $SubArray)
{
foreach ($SubArray as $key => $value)
{
$sql .= "UPDATE kunden SET ".$key."='".$value."' WHERE id=**?????????**";
}
}
答案 0 :(得分:2)
foreach ($_POST['changed'] as $SubArray)
{
$id = $subArray['recid'];
$values = array();
foreach ($SubArray as $key => $value)
{
if($key != 'recid')
{
$values[] = $key . '=' . $value;
}
$sqlValues = implode(', ', $values);
}
$sql = "UPDATE kunden SET " . $sqlValues . " WHERE id='" . $id . "'";
//execute query here
}
答案 1 :(得分:0)
只需使用:
if ($key === 'recid') continue;
$sql .= "UPDATE kunden SET ".$key."='".$value."' WHERE id='".$SubArray['recid']."'";
而不是
$sql .= "UPDATE kunden SET ".$key."='".$value."' WHERE id=**?????????**";
答案 2 :(得分:-1)
试试这个:
foreach ($_POST['changed'] as $SubArray) {
foreach ($SubArray as $key => $value) {
if ($key === 'recid') continue;
$sql = "UPDATE kunden SET $key = $value WHERE id = '$SubArray[recid]'";
}
}
此代码不适用于制作。您必须转义每个$_POST
变量或使用PDO占位符。
更新(PDO占位符示例):
$dsn = 'mysql:dbname=kunden;host=127.0.0.1';
$enc = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'");
$dbh = new PDO($dsn, $user, $pass, $enc);
foreach ($_POST['changed'] as $SubArray) {
foreach ($SubArray as $key => $value) {
if ($key === 'recid') continue;
$sql = "UPDATE kunden SET $key = :value WHERE id = :recid";
$stmt = $dbh->prepare($sql);
try {
$stmt->execute(array(':value' => $value, ':recid' => $SubArray['recid']));
} catch (PDOException $e) {
// error processing
}
}
}