【问题标题】:Php mysql insert/update from jsonphp mysql 从 json 插入/更新
【发布时间】:2018-10-10 12:31:55
【问题描述】:

您好,我在向 mysql 工作时插入数据时遇到问题,但如果不存在数据,我需要创建如果存在则更新所有行。 现在每次刷新页面后添加相同的数据但不更新。

$conn = mysql_connect("127.0.0.1", "root","") or die(mysql_error());
mysql_select_db("youtuberiai", $conn);

echo "Connected successfully <br /><br />";

$url = 'https://www.googleapis.com/youtube/v3/channels?id=ID&part=snippet%2Cstatistics&key=KEY';
$content = file_get_contents($url);
$json = json_decode($content, true);

foreach($json as $row);
foreach($json['items'] as $row)
{
    $idd = $row['id'];
    $title = $row['snippet']['title'];
    $description = $row['snippet']['description'];
    $viewCount = $row['statistics']['viewCount'];
    $subscriberCount = $row['statistics']['subscriberCount'];
    $sql = "INSERT INTO vartotojai(idd, title, description, viewCount, subscriberCount) VALUES('$idd', '$title','$description','$viewCount','$subscriberCount') 
    ON DUPLICATE KEY UPDATE idd='$idd', title='$title', description='$description', viewCount='$viewCount', subscriberCount='$subscriberCount';
    ";
    mysql_query("SET NAMES utf8");
    if(!mysql_query($sql,$conn))
    {
        die('Error : ' . mysql_error());
    }
}

【问题讨论】:

  • 你的idd是主键吗?
  • id INT 50 AUTO_INCREMENT 它是主要 idd 它是来自 json 的频道 id。

标签: php mysql json insert


【解决方案1】:

id设为唯一。然后只有重复查询获得角色。如果该字段中的值已经存在,则该字段将被更新。

【讨论】:

    猜你喜欢
    • 2019-04-03
    • 1970-01-01
    • 2016-04-01
    • 2018-12-04
    • 2012-08-23
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多