使用带有PDO的数组更新多个MySQL表

时间:2018-12-31 23:18:49

标签: php post pdo

Updating multiple MySQL table columns using arrays with PDO非常相似。

但是我使用

使用复杂的表格
<input name="data[Name]" type="text" more stuff>

更新只是给我一个空白页面而没有任何错误?

NB:使用MySQLi并运行良好,只是更新为PDO。

$ data2返回一个正确的数组。

这可能是订购商品吗? IE输出必须匹配列顺序?

已与Updating multiple MySQL table columns using arrays with PDO一起分析了https://guwii.com/bytes/update-multiple-database-columns-using-pdo/

*****更新******

$data = $_POST[data];

$data1 = array(ARRAY INFO HERE);

$data2 = array_merge($data, $data1);

function buildBindedQuery($fields){    
    end($fields);
    $lastField = key($fields);
    $bindString = ' ';
    foreach($fields as $field => $data2){
        $bindString .= $field . '=:' . $field;
        $bindString .= ($field === $lastField ? ' ' : ',');
    }

    return $bindString;                                             
}

$query = 'UPDATE details SET '.buildBindedQuery($data2).' WHERE id='.$_POST['id'].'';
$result = $conn->prepare($query);
$result->execute($data2);

1 个答案:

答案 0 :(得分:0)

我认为这段代码可以为您提供帮助

        $data = $_POST['data'];

        $data1 = array ("Array info here");

        $data2 = array_merge($data, $data1);

        function buildBindedQuery($fields){
        end($fields);
        $lastField = key($fields);
        $bindString = ' ';
        foreach($fields as $field => $data2){
        $bindString .= $field . '=' . $field;
        $bindString .= ($field === $lastField ? ' ' : ',');
         }
         return $bindString;                                                
        }

        $servername = "localhost";
        $username = "";
        $password = '';
        $dbname = "";

        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, 
                        $password);

        $variable = buildBindedQuery($data2);
        $variable2 = explode(",", $variable);

        foreach($variable2 as $var) {
            $va = explode("=", $var);
            $query = "UPDATE usuario SET $va[0]='". $va[1] ."' WHERE id=2";

            $result = $conn->prepare($query);

            $result->execute();
        }