[英]Use PHP to insert JSON to MySQL table
我需要使用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_map
和array_keys
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.