dsla94915 2019-03-03 14:28
浏览 96

如何在php和mysqli中修复重复的标记名称

I don't know how to explain it, maybe this is understandable. I have 2 table:

  1. Table tags: (tagID: '1', '2', '3') (tagName: 'a', 'b', 'b')
  2. Table tag_posts: (postID: '1', '1', '2') (tagID: '1', '2', '3')

Output: Post 1 tagged (a[id=1], b[id=2]) and post 2 tagged (b[id=3])

But, i want result like this:

  1. Table tags: (tagID: '1', '2') (TagName: 'a', 'b')

  2. Table tag_posts: (postID: '1', '1', '2') (tagID: '1', '2', '2')

Output: Post 1 tagged (a[id=1], b[id=2]) and post 2 tagged (b[id=2])

I want on table "tags" tag name, b is 2; not b = 2 and b = 3 (not double tag name)

Php

$last_post_id = mysqli_insert_id($connect);

foreach($tags as $tag){
  $sql = mysqli_query($connect, "SELECT * FROM tb_tags WHERE tagName = '$tag'") or die(mysqli_error());
  $row = mysqli_fetch_array($sql);
  if($row == NULL){
    mysqli_query($connect, "INSERT INTO tb_tags (tagName) VALUES ('$tag')") or die(mysqli_error());
    $last_tag_id = mysqli_insert_id($connect);
    mysqli_query($connect, "INSERT INTO tb_tag_posts (postID, tagID) VALUES ('$last_post_id', '$last_tag_id')") or die(mysqli_error());
  }else{
  // if tags name exists do nothing and take the existing id tag
    mysqli_query($connect, "INSERT INTO tb_tag_posts (postID, tagID) VALUES ('$last_post_id', '".$row['tagID']."')") or die(mysqli_error());
  }
}
  • 写回答

1条回答 默认 最新

  • 普通网友 2019-03-04 07:58
    关注

    mysqli_fetch_array: Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter. from http://php.net/manual/en/mysqli-result.fetch-array.php

    I think that you need to have your code like this: if($row == null){

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP