使用多维数组在Mysql上重复存储数据

时间:2017-05-31 03:36:58

标签: php mysql multidimensional-array

如何在mysql上存储datatable.php数组?我有以下代码,

multidimensional

它会产生:

if (isset($_POST['submit'])) {

    echo "<pre>"; var_dump($_POST); echo "</pre>";

    $nama = $_POST['nama'];
    $age = $_POST['age'];
    $array = array('nama' => $nama, 'age' => $age);

}

存储到mysql:

array(6) {
  ["nama"]=>
  array(2) {
    [0]=>
    string(6) "batman"
    [1]=>
    string(9) "spiderman"
  }
  ["age"]=>
  array(2) {
    [0]=>
    string(2) "40"
    [1]=>
    string(2) "35"
  }
}

我有谷歌关于此并提出上述代码,但它将复制如下数据,

require_once('db_connection/connection.php');

foreach ($array as $key => $value) {
    $stmt = $conn->prepare("INSERT INTO tanggungan (name, age) VALUES (?, ?)");
    $stmt->bind_param("ss", $nama, $age);

    foreach ($value as $index => $value) {
        $nama = $array['nama'][$index];
        $age = $array['age'][$index];   
    }

    $stmt->execute();
}

echo "New records created successfully";

$stmt->close();
$conn->close();

如果我错误地使用它或不是最佳实践,请道歉。仍在学习网络编程。

1 个答案:

答案 0 :(得分:1)

这是一种更好的方法:

require_once('db_connection/connection.php');

for ($i = 0; $i < count($array); $i++) {

    $stmt = $conn->prepare("INSERT INTO tanggungan (name, age) VALUES (?, ?)");
    $stmt->bind_param("ss", $array['nama'][$i], $array['age'][$i]);

    $stmt->execute();
    $stmt->close();
}

echo "New records created successfully";
$conn->close();