0

我想将数组值写入我的数据库,例如:

“更新 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循环执行此操作时,recidget 也作为字段名称 - 但这不应该发生。

foreach ($_POST['changed'] as $SubArray)
{
    foreach ($SubArray as $key => $value)
    {
        $sql .= "UPDATE kunden SET ".$key."='".$value."' WHERE id=**?????????**";
    }       
}
4

3 回答 3

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
}
于 2013-09-02T17:15:33.357 回答
0

只需使用:

if ($key === 'recid') continue;
$sql .= "UPDATE kunden SET ".$key."='".$value."' WHERE id='".$SubArray['recid']."'";

代替

$sql .= "UPDATE kunden SET ".$key."='".$value."' WHERE id=**?????????**";
于 2013-09-02T17:14:58.580 回答
-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
        }
    }
}
于 2013-09-02T17:12:16.463 回答