在php中将关联数组插入MySQL数据库

GKu*_*mar 1 php mysql

我有一个名为的数组$output,其中包含:

Array
(
    [0] => Array
        (
            [0] => J Arora
            [1] =>  India
        )

    [1] => Array
        (
            [0] => J Ramuj
            [2] =>  Russia
        )

    [2] => Array
        (
            [1] =>  KJ Tris
            [2] =>  Germany
        )

)
Run Code Online (Sandbox Code Playgroud)

我怎样才能像这样将这些数据插入到mysql数据库表中

---------------
name   | country
-------|---------
J Arora|India
-------|--------
J Ramuj|Russia
-------|--------
KJ Tris|Germany
-------|--------
Run Code Online (Sandbox Code Playgroud)

我无法从给定数组中单独获取这些值,因为它们的索引不按顺序排列。

Tol*_*ios 5

只需用 a 循环它foreach,并使用 PHP 本机函数(如current()和 )end()来获取元素。鉴于数组中始终只有两个元素,这应该可行

foreach ($output as $v) {
    echo current($v); // Name
    echo end($v); // Country
}
Run Code Online (Sandbox Code Playgroud)

调整它来构建您的查询并在循环内执行它。在循环内你可以做

foreach ($output as $v) {
    $sql = "INSERT INTO table (`name`, `country`) VALUES ('".current($v)."', '".end($v)."')";
    // TODO: Execute query
}
Run Code Online (Sandbox Code Playgroud)

您还应该注意,任何使用变量的查询都应该使用带有占位符的准备好的语句。MySQLi 和 PDO 都支持这一点。


使用准备好的语句

之前构建查询,并在使用绑定的适当变量循环它时执行它。

PDO 示例:

$stmt = $pdo->prepare("INSERT INTO table (`name`, `country`) VALUES (:name, :country)");
foreach ($output as $v) {
    $stmt->execute(array("name" => current($v), "country" => end($v));
}
Run Code Online (Sandbox Code Playgroud)

MySQLi 示例:

$stmt = $mysqli->prepare("INSERT INTO table (`name`, `country`) VALUES (?, ?)");
foreach ($output as $v) {
    $name = current($v);
    $country = end($v);
    $stmt->bind_param("ss", $name, $country);
    $stmt->execute();
}
Run Code Online (Sandbox Code Playgroud)