【问题标题】:If the value of a object is empty in a JSON file, it takes previous value如果 JSON 文件中对象的值为空,则取之前的值
【发布时间】:2017-11-23 22:40:59
【问题描述】:

我正在使用来自 JSON 文件的 PDP Prepared PDO 语句在 SQL 数据库中插入值。

这就是我的代码:

$requestno = 8
$maxrequest = 15
while ($requestno < $maxrequest)
{
    $response = file_get_contents("https://api.themoviedb.org/3/movie/".$requestno."?api_key=456cec7xxxxxxxxxxxxxe0c834a");
    if ($response != FALSE) {
        $response = json_decode($response, true);
    }

   $requestno++;

   <?php

   try {

       // prepare sql and bind parameters
       $stmt = $conn->prepare("INSERT INTO TABLE (firstname) 
                               VALUES (:firstname)");
       $stmt->bindParam(':firstname', $firstname);

       // insert a row
       if ( $response["firstname"] != ""        )
       $tagline = $response["firstname"];
       $stmt->execute();

       echo "New records created successfully";
    }
    catch(PDOException $e)
    {
       echo "Error: " . $e->getMessage();
    }
   $conn = null;
}
?>

您可以看到 JSON 文件的 url 包含“.$requestno.”,所以我正在从多个 JSON 文件中检索数据。

那么这里会发生什么,如果 JSON 文件中的 firstname 为空,MYSQL 会插入之前的 JSON 文件 firstname。如何解决?

如果您需要更多信息,请告诉我。

【问题讨论】:

  • 您自己尝试过什么解决方法?你试过在file_get_contents之前设置$response = false吗?
  • 在循环开始时清空变量。 $firstname = ''; 和 ^^
  • 所有 JSON 文件都有一定的价值。所以,它永远不会是假的
  • 让我试试 Jon 的解决方案

标签: php mysql json loops pdo


【解决方案1】:

您需要在每个循环开始时重置变量 $firstname,正如 JonStirling 在他的 cmets 中提到的,如下所示,

while ($requestno < $maxrequest)
{
  $firstname = '';
  //your remaining code here
}

问题:由于您没有重置您的值,它会采用在上一次迭代中分配给它的值

【讨论】:

  • 我收到此错误错误:SQLSTATE[HY000]:一般错误:1366 不正确的整数值:'' for column 'firstname' at row 1
  • 从哪里获得循环中 $firstname 的值。我假设你会从 $response 中得到它们。可能是您没有从响应中获得 $firstname,甚至您没有获得 $response 本身
  • 我错了,我从 $firstname 那里得到了一个号码...修复了它。
猜你喜欢
  • 2020-11-03
  • 2018-03-06
  • 2017-08-07
  • 2017-11-27
  • 1970-01-01
  • 2017-12-28
  • 2022-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多