gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:36:03 25 4
gpt4 key购买 nike

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

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

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

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

)

如何将这些数据插入mysql数据库表中

---------------
name | country
-------|---------
J Arora|India
-------|--------
J Ramuj|Russia
-------|--------
KJ Tris|Germany
-------|--------

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

最佳答案

只需使用 foreach 循环它,并使用 current()end() 等 PHP 原生函数来获取您的元素。鉴于您的数组中始终只有两个元素,这应该可行

foreach ($output as $v) {
echo current($v); // Name
echo end($v); // Country
}

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

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

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


使用准备好的语句

之前构建查询,并在绑定(bind)适当变量的情况下循环执行它。

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));
}

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();
}

关于php - 在php中将关联数组插入MySQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41300008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com