douwu8060 2013-06-20 11:06
浏览 154
已采纳

使用CSV插入数据和/或更新数据库


So I've been working on this for some time, but i cant seem to figure out how to get it to work.

I want to update the prices of a product in the database if the product id is there, if it's not there i want it to insert the new id and it's prices.

Using the code below it updates the database, however it does not insert anything if the id is not there.

Any clues on what's gone wrong?

With thanks
Jim

EDIT

This works for me:

$count = mysql_num_rows(mysql_query("SELECT id FROM products WHERE id = '$id'"));



            if ($count == 1){

            mysql_query("UPDATE products SET price='$price',ordprice='$ordprice' WHERE id='$id'");

            }elseif($count == 0){

            mysql_query("INSERT INTO products (id,price,ordprice) VALUES ('$id','$price','$ordprice')");
            }

/EDIT

if(isset($_POST['submit']))
    {
        $file = $_FILES['file']['tmp_name'];

        $handle = fopen($file,"r");
        while(($fileop = fgetcsv($handle,10000,";")) !== false)
        {
            $id = $fileop[0];
            $price = $fileop[1];
            $ordprice = $fileop[2];


            $count = mysql_num_rows(mysql_query("SELECT id FROM products WHERE id = '$id'"));



            if ($count = $id){

            mysql_query("UPDATE products SET price='$price',ordprice='$ordprice' WHERE id='$id'");

            }elseif($id != $count){

            mysql_query("INSERT INTO products (id,price,ordprice) VALUES ('$id','$price','$ordprice')");
            }
  • 写回答

2条回答 默认 最新

  • dongzhuo7291 2013-06-20 11:24
    关注

    Besides what Hugh Downer said, you're facing another problem.

    You're assigning to $count the value returned by mysql_num_rows which seems not to be the value you want.

    You're comparing $count to $id to find out if they match. If I assume correctly that your id in the database is unique, $count will never be other than 0 or 1.

    So try this:

    if ($result = mysql_query("SELECT id FROM products WHERE id = $id")) {
        $row = mysql_fetch_array($result);
        $id2 = $row['id'];
    }
    else {
        $id2 = NULL;
    }
    
    if ($id == $id2) {
        // match found, do the insert magic
    }
    else {
        // update here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?