dtv7174
dtv7174
2018-10-10 12:31

从json插入/更新Php mysql

已采纳

hello i have a problem insert data to mysql working but i need if not exist data create if exist update all row. Now after each refresh page add same data but not updating.

$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());
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doubu1853 doubu1853 3年前

    make the id as unique. Then only duplicate query gets the role. If the value in that filed already exist, then then that field will be updated.

    点赞 评论 复制链接分享

相关推荐