循环POST数组并更新数据库

时间:2013-12-20 14:44:57

标签: php mysql arrays mysqli

我有一个PHP页面,它根据从MySQL数据库收到的数据动态生成表单。例如,假设Logo URL有一个条目,它将如下所示:

configName = MainLogoURL; configValue = "blah"; 

这是一般的想法。我正在努力的任务是更新数据库,所有数据都通过POST请求发送。最终结果是这样的

Array ( 
       Array ( configName => "MainLogoURL", configValue => "BLAH 2" )
)

显然,每个变量的结构中会有更多的数组。如果有更有效的方式,那么请你告诉我(以及如何做)或者你能告诉我怎么做。

2 个答案:

答案 0 :(得分:0)

正如Yatin所说,foreach($_POST as $key => $value)是一个良好的开端。

你应该看一下MySQL documentation for REPLACE statements。这应该允许您使用单个语句插入多个值。

PHP manual has PDO examples让您入门,并且有一些工作PDO multiple insert examples here

答案 1 :(得分:0)

就像有人说的那样...使用pdo,在你的情况下,这应该是这样的:

$dbh = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $dbh->prepare("INSERT INTO myTable (configName, configValue) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

$myArray = Array ( 
   Array ( "configName" => "MainLogoURL", "configValue" => "BLAH 2" )
)


foreach($myArray as $arr)
{
    $name  = $arr['configName'];
    $value = $arr['configValue'];
    $stmt->execute();
}

张贴了这个,因为你说你想要一个样本:)

相关问题