Home  >  Q&A  >  body text

PHP inserts data into the MySQL database in a loop. How to determine whether each item is inserted successfully?

Just like the title.

            while(! feof($file)){
                $data= fgets($file);//fgets()函数从文件指针中读取一行
                $res = $this->Model->function($data);//插入数据的方法
            }
            //比如这种的怎么判断每一行都插入成功
阿神阿神2668 days ago869

reply all(6)I'll reply

  • 学习ing

    学习ing2017-06-30 09:55:58

    //Define variable num
    $num = 0;
    while (! feof($file)) {

    $data= fgets($file);//fgets()函数从文件指针中读取一行
    $res = $this->Procesratio->promction($data);
    
    // 直接在这里判断
    if (!$res) {
        $num += 1;
    }

    }

    // Judge the value of num here
    if ($num == 0) {

    // 全部成功

    } else {

    // $num即为失败条数

    }

    reply
    0
  • 怪我咯

    怪我咯2017-06-30 09:55:58

    Start the transactiontransaction, and as long as there is an error, it will rollback and throw an exception

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-30 09:55:58

    if($res == true){
       echo "success";
    }else{
        echo "fault";
    }

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-30 09:55:58

    while(! feof($file)){
        $data= fgets($file);//fgets()函数从文件指针中读取一行
        $res = $this->Model->function($data);//插入数据的方法
        if($res){
            echo "success!";
        }else{
            echo "error!。。。try again....";
            $this->Model->function($data)
        }
    }

    After the insertion is successful, data will be returned. Just make a judgment based on the return! !

    reply
    0
  • 高洛峰

    高洛峰2017-06-30 09:55:58

    For this large amount of data insertion method, if the online business is not so busy, you can consider inserting in batches. After batch inserting, the returned result is the number of affected rows. The returned results are easier to search and the efficiency will be higher than this. Or business, simple violence.

    reply
    0
  • 黄舟

    黄舟2017-06-30 09:55:58

    It is recommended to use things, so that you can at least ensure the consistency of the data.

    reply
    0
  • Cancelreply