gpt4 book ai didi

javascript - 使用PHP将JSON插入MySQL表

转载 作者:行者123 更新时间:2023-11-29 07:06:14 25 4
gpt4 key购买 nike

我需要使用 PHP 将 Javascript 对象插入到新的 MySQL 表中。我的对象采用以下形式:

{
rowA:[A1,A2,A3],
rowB:[B1,B2,B3],
rowC:[C1,C2,C3],
}

我还有一个列名称数组:

$columns = array("col1","col2","col3");

我需要使用这些数据创建并填充以下格式的 MySQL 表:

      col1 col2 col3
rowA A1 A2 A3
rowB B1 B2 B3
rowC C1 C2 C3

我可以访问我的服务器并创建一个表,但我仍然不确定如何处理 JSON:

$str = file_get_contents('barchartData/US-HI.json');
$json = json_decode($str, true);
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "CREATE TABLE testTable (
// not sure how to specify column, row, and cell values from the JSON...
)";

我对 PHP 相当陌生,无法在 PHP 中获取代码来读取 JSON 键并将它们设置为 MySQL 行值。

最佳答案

正如之前的评论中提到的,我建议拆分该问题。表创建不应该成为问题,因为这些值不是来自 JSON 文件。

因此,我们首先验证您的 JSON 文件。您可以使用在线工具来完成此操作。查看下面的代码,您可以在当前脚本之外运行该代码。这不是最优雅的解决方案,但我认为它会帮助您最好地理解该解决方案。

<?php

echo '<pre>'; // For testing purposes.

// Convert the array to comma separated values as is
// required by the MySQL insert statement.
$fields = array("col1","col2","col3");
$imploded_fields = implode(',', $fields);

$json = '{"rowA":["A1","A2","A3"], "rowB":["B1","B2","B3"], "rowC":["C1","C2","C3"]}';
$decoded = json_decode($json);

foreach ($decoded as $d) {

$values = implode(',', $d);
$statement = "INSERT INTO `table` ($imploded_fields) VALUES ($values)";

echo $statement; // Change this to actually execute the statement
}

希望这是有道理的。如果您想进一步优化此解决方案,请查看 array_maparray_keys 等有用的函数。

关于javascript - 使用PHP将JSON插入MySQL表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510389/

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