使用PDO将多维POST保存到数据库

use*_*479 0 php arrays

我正在学习如何使用PDO,到目前为止它一直很好.有一个小问题我似乎无法解决.

我有一个包含2个字段的html表单,但是单击a +会添加另外2个字段.

Array ( [domainname] => Array ( [0] => google [1] => facebook [2] => stackoverflow ) [domainextension] => Array ( [0] => nl [1] => eu [2] => com ) ) 
Run Code Online (Sandbox Code Playgroud)

我需要的是将它插入我的数据库.显然"google"属于"nl"等.

$post = $_POST;
try {
    // Create a new PDO object (start database connection)
    $dbh = new PDO('mysql:host=localhost;dbname=domains', $user, $pass);

    // Build the query
    $sql = "INSERT INTO domain_list (name, ext, status)
            VALUES (:name,:ext,:status)";

    // Prepare the query
    $q = $dbh->prepare($sql);

    // Execute the query
    $q->execute(array(':name' => $name, 
                      ':ext' => $ext, 
                      ':status' => $status));

    // End the database connection connection
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
Run Code Online (Sandbox Code Playgroud)

状态:这只是"活动"这个词,所以我可以用它来选择.

我知道我只需要创建一个foreach所以所有行都更新到数据库,但我不知道最好的方法.

提前致谢.

Dam*_*vic 5

你应该尝试类似的东西:

for ($i=0;$i<count($_POST['domainname']);$i++) {
  $name = $_POST['domainname'][$i];
  $ext = $_POST['domainextension'][$i];
  $status = $_POST['status'][$i]; //Since you have not provided what $status is, this is my guess
  $q->execute(array(':name' => $name, 
                      ':ext' => $ext, 
                      ':status' => $status));
}
Run Code Online (Sandbox Code Playgroud)