我一直在关注如何将 JSON 数据插入 MySQL 表的解决方案 ( How to insert json array into mysql database)。代码似乎运行正常,但它仍然返回一个空数据集。
我目前正在检验一个假设,我的 JSON 文件中有 100,000 条记录。我创建了一个类似的 JSON 文件,其中只有三个记录,我认为文件的大小可能阻碍了它,但也没有用。
我已经检查了我的数据库名称、表名称和行名称,但显示的代码是正确的。有什么指点吗?
<?php
$json = file_get_contents('E:\xampp\htdocs\MOCK_DATA.json');
$obj = json_decode($json, true);
$connection = mysqli_connect("localhost", "root", "");
mysqli_select_db($connection, "et_test") or die('Couldnt connect database');
foreach($obj as $item)
{
mysqli_query($connection, "INSERT INTO 'et_test'.'test' (first_name, last_name, colour, country, city)
VALUES ('".$item['first_name']."','".$item['last_name']."','".$item['colour']."','".$item['country']."','".$item['city']."')");
}
mysqli_close($connection);
?>
最佳答案
根据 OP 希望关闭问题并标记为已解决:
这是有问题的代码段'et_test'.'test'
使用反引号,因为在表名周围使用引号是错误的标识符:
SQL
mysqli_query($connection, "INSERT INTO `et_test`.`test` ...
使用 or die(mysqli_error($connection))
到 mysqli_query()
,以获得“真正的”错误。
考虑开始使用 prepared statements , 或 PDO with prepared statements .
就目前而言,您当前的代码是对 SQL injection 开放的.
关于php - 将 JSON 数据插入 MySQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26895024/