douduan7295 2014-09-01 07:58
浏览 28
已采纳

如果数据库中存在字段,则更新价格,否则插入全部

i need somehow to check if field exist in db, and then if exist, just update price, if not, insert fields. I am using simplxml for parsing data to db from xml.

here is my code without if statement, just insert into two databese.

I need to check from db products if ident exist, so if not exist, do all that code down, if exist just update price in db products

foreach ($lib->product as $data) {
    $manufacturer = (string) $data->manufacturer;
    $ident = (string) $data->id;
    $name = (string) $data->name;
    $category = (string) $data->category;
    $subcategory = (string) $data->subcategory;
    $price = (int) ($data->price * 1.2 * 1.4 * 1.1);
    $image = (string) $data->images->image[0];


    $insert = $db->prepare('INSERT INTO products (ident, manufacturer,name,category,subcategory,price,image) VALUES (?, ?, ?, ?, ?, ?, ?)');
    $insert->bind_param('sssssss', $ident, $manufacturer, $name, $category, $subcategory, $price, $image);
    $insert->execute();


    foreach($data->specifications->attribute_group as $group) {
        $attribute_group = (string) $group->attributes()['name'];

        foreach($group as $attr) {
            $attribute = (string) $attr->attributes()['name'];
            $value = (string) $attr->value;
            $insert = $db->prepare('INSERT INTO spec (attr_group,attr_name, attr_value, product_id) VALUES (?, ?, ?, ?)');
            $insert->bind_param('ssss', $attribute_group, $attribute, $value, $ident);
            $insert->execute();

        }

    }

}

  • 写回答

2条回答 默认 最新

  • dpe77294 2014-09-01 08:12
    关注

    To do in one query, look up MySQL's ON DUPLICATE KEY UPDATE functionality for INSERT.

    Then use $insert->rowCount() if you're using PDO or $insert->affected_rows for mysqli.

    If the first insert tried to already insert a key that existed and updates a value, then rowCount()/affected_rows will be 2; if it just inserted a record then rowCount()/affected_rows will be 1. It will be 0 if the INSERT was unsuccessful.

    e.g. for PDO:

    switch($insert->rowCount()) {
        case 2:  // UPDATE occurred thanks to 'ON DUPLICATE UPDATE KEY'
            // SOME CODE HERE IF YOU LIKE
            break;
        case 1:  // INSERT occurred as no duplicate
            // CODE TO INSERT INTO SECOND TABLE
            break;
        case 0:
        default:
            // NEITHER THE ABOVE OCCURRED SO CODE TO HANDLE ERROR
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题