首页 > 解决方案 > 将 Json 文件加载到表时结果不一致

问题描述

我很难理解为什么在尝试将JSON文件数据插入新表时得到的结果。问题是一个JSON文件可以正常工作并填充表格,而另一个JSON文件则不能。我正在使用Xamppphpadmin,但我不知道为什么我的问题仍然存在。表的创建适用于任何JSON文件,但数据的插入是主要问题。

.php 文件:

include("dbCon.php");

$fname=$_POST['fname'];

if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
  $sql = "CREATE TABLE `".$fname."`(
  id bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  imgurl VARCHAR(255) NOT NULL,
  content VARCHAR(20000) NOT NULL
  )";

  if ($conn->query($sql) === TRUE) {
     echo "Table ".$fname." created successfully";
  } else {
     echo "Error creating table: " . $conn->error;
  }

  $json = file_get_contents('../jsonFIle/'.$fname.'.json');
  $array = json_decode($json, true);

  echo var_dump($fname);
  foreach($array as $row) {
   $sql = "INSERT INTO `".$fname."`(title, imgurl, content) VALUES('".$row["title"]."', '".$row["imgurl"]."', '".$row["content"]."')";
   mysqli_query($conn, $sql);
 
  }
  echo var_dump($array);

    
$conn->close();

json 文件: test.json

[
        {
            "title":"test1", 
            "imgurl":"test1",
            "content":"test1"
        },
        {
            "title":"test2", 
            "imgurl":"test2",
            "content":"test2"
        },
        {
            "title":"test3", 
            "imgurl":"test3",
            "content":"test3"
        }
]

Json 文件: newmainnews.json

[
        {
            "title":"NASA's record-breaking Lucy asteroid mission gearing up for October launch", 
            "imgurl":"record.jpg",
            "content":"Lucy is scheduled to launch atop a United Launch Alliance Atlas V rocket from Florida's Cape Canaveral Space Force Station on Oct."
        },
        {
            "title":"Mars on the cheap: Scientists working to revolutionize access to the Red Planet", 
            "imgurl":"mars.jpg",
            "content":"Spotting Jupiter is a breeze this week for the naked eye as it reaches its biggest and brightest moment in the night sky. Telescope-hunters will also get a treat looking for moons and atmospheric bands. The gas giant planet will be at opposition today (Aug. 19), meaning it is directly opposite the sun in Earth's sky. Jupiter also makes its closest approach of the year to Earth during opposition. The planet will appear at magnitude -2.9, well within naked-eye range and outshining any star in Earth's sky except, of course, for the sun."
        },
        {
            "title":"Jupiter's winds of change show increased storm speeds in Great Red Spot", 
            "imgurl":"jupiter.jpg",
            "content":"The long-running telescope has been studying the Great Red Spot — a major storm on Jupiter — that is shrinking for mysterious reasons. Alongside that, researchers just uncovered huge changes in wind speeds within the massive storm.Jupiter takes 12 Earth years to orbit the sun. During the Jovian year between 2009 and 2020."
        }
]

var_dumptest.json的回声:

数组(3) { [0]=> 数组(3) { ["title"]=> string(5) "test1" ["imgurl"]=> string(5) "test1" ["content"]=> string(5) "test1" } [1]=> array(3) { ["title"]=> string(5) "test2" ["imgurl"]=> string(5) "test2" ["content" ]=> string(5) "test2" } [2]=> array(3) { ["title"]=> string(5) "test3" ["imgurl"]=> string(5) "test3" [ "内容"]=> 字符串(5) "test3" } }

var_dumpnewmainnews.json的回声:

array(3) { [0]=> array(3) { ["title"]=> string(74) "NASA 破纪录的露西小行星任务准备 10 月发射" ["imgurl"]=> string(10 ) "record.jpg" ["content"]=> string(130) "Lucy 计划于 10 月从佛罗里达州卡纳维拉尔角太空部队站搭乘联合发射联盟 Atlas V 火箭发射。" } [1]=> array(3) { ["title"]=> string(79) "便宜的火星:科学家们致力于彻底改变进入红色星球" ["imgurl"]=> string(8) " mars.jpg" ["content"]=> string(539) "本周发现木星对肉眼来说是一件轻而易举的事,因为它在夜空中达到了它最大和最亮的时刻。望远镜猎人也将得到一种寻找的享受卫星和大气带。这颗气态巨行星将在今天(8 月 19 日)处于冲日状态,这意味着它与地球天空中的太阳直接相对。在冲日期间,木星也最接近地球。这颗行星将以 -2.9 等星等出现,完全在肉眼范围内,并且比地球天空中的任何恒星都要亮,当然,太阳除外。” } [2]=> array(3) { ["title"]=> string(71) "木星的变化之风显示大红斑的风暴速度增加" ["imgurl"]=> string(11) "jupiter.jpg" ["content"]=> string(327) "长期运行望远镜一直在研究大红斑——木星上的一场大风暴——由于神秘的原因正在缩小。除此之外,研究人员刚刚发现了大风暴中风速的巨大变化。木星绕太阳运行需要 12 个地球年。在 2009 年到 2020 年的木星年。” } }

test.json文件正确填充表格,但newmainnews.json不插入任何内容。

我怀疑JSON文件有问题。无论哪种方式,正如我之前所说,我完全一无所知,任何澄清或帮助将不胜感激。

标签: phparraysjsondatatablexampp

解决方案


这段代码很容易受到SQL 注入的影响,我相信这实际上是导致您的问题的原因。

您的示例文件包含使用单引号 ( ') 作为撇号的字符串。因为您使用基本的字符串连接来构建 SQL 查询,所以当这些单引号成为查询的一部分时,您会产生无效的 SQL。

例如,让我们采用第一项,但为了便于阅读示例,我将缩短它:

{
    "title":"NASA's Lucy asteroid mission", 
    "imgurl":"record.jpg",
    "content":"Lucy is scheduled to launch."
}

然后,您尝试使用以下代码创建 SQL 查询:

$sql = "INSERT INTO `".$fname."`(title, imgurl, content) VALUES('".$row["title"]."', '".$row["imgurl"]."', '".$row["content"]."')";

结果查询将如下所示:

INSERT INTO `newmainnews`(title, imgurl, content) VALUES ('NASA's Lucy asteroid mission', 'record.jpg', 'Lucy is scheduled to launch.')

现在,查看该部分中的第一项VALUES。StackOverflow 的语法高亮实际上在这里很有帮助。由于 中的单引号NASA's,您正在创建无效 SQL,因为第一个值本质上成为字符串 "NASA",后面跟着s Lucy asteroid mission',MySQL 将解释为无效 SQL ,因为单引号关闭了 title 字符串的开头

如果您不熟悉 SQL 注入,这是最简单的情况之一,有人可以注入包含引号的字符串以关闭输入字符串,然后他们可以注入任意恶意 SQL 代码。例如,如果您的一篇文章标题更改为:

{
   "title":"NASA','',''); DROP TABLE `newmainnews`; --",
   "imgurl": "",
   "content": ""
}

我没有对其进行测试,但这应该会导致您的表被删除。

解决这个问题的方法是让您自己熟悉转义输入,并确保您不只是盲目地获取输入字符串并将它们直接放在 SQL 中。我强烈建议您尝试改用PDO 准备语句。如果你被卡住了mysqli我认为你也可以使用准备好的语句,但我对此知之甚少。

自己做一些额外的研究,在谷歌上搜索“准备好的语句”和“如何防止 SQL 注入”等主题。


推荐阅读