如何在保存到数据库之前检查循环中的所有数据

时间:2017-10-01 04:10:46

标签: php mysql laravel laravel-5.4

现在在我的控制器中它看起来像这样

assume that $available = [ 1,2,3,4 ]

    for ($i=0; $i < 3; $i++) {
      if($available < 3){
        echo 'success';
        $database->save();
      }else{
        echo 'error';
      }
    }

这将输出成功成功成功错误

它将在数据库中保存3个成功,如何检查我是否有1个错误它不会保存任何数据?

现在我正在使用

   $errors = false;
    DB::transaction(function () use ($count,$request,$a,$errors) {
        for ($i=0; $i < $count; $i++) {
            $warehouse_products_sell = New Warehouse_products_sell;
            $id_w = $request->input('idw');
            $id_c = $request->get('id_c')[$i];
            $id_p = $request->get('id_p')[$i];
            $qty = $request->input('quantity_box')[$i];
            $price = $request->input('price')[$i];
            $available = $this->check_stock($id_w, $id_p, $qty);
          if($available > 0){
            $warehouse_products_sell->add_by = $request->input('add_by');

            $warehouse_products_sell->id_w = $id_w = $request->input('idw');
            $warehouse_products_sell->id_c = $request->get('id_c')[$i];
            $warehouse_products_sell->id_p = $id_p = $request->get('id_p')[$i];
            $warehouse_products_sell->quantity_box = $qty = $request->input('quantity_box')[$i];
            $warehouse_products_sell->price = $request->input('price')[$i];
            $warehouse_products_sell->serial_num = $a;
            $available = $this->check_stock($id_w, $id_p, $qty);
            $warehouse_products_sell->save();
          }else{

            echo "error";
            $errors = true;

            throw new Exception('Error');
          }
        }
    });
    if ($errors) {
       return redirect('URL');
    }else{
        return 'x';
    }

1 个答案:

答案 0 :(得分:1)

您可以使用交易。看看here

您的代码将更改为此

while True:

    herb=input("Herb: ")

    database=open("db.txt")

    for line in database:
        record = line.split('|')
        if record[0] == herb:
            found = True
            break
        else:
            found = False
            continue

    if found == False:
        print("No herbs in database.")
        print('')
    else:
        print(record[0]) 
        print(record[1]) 
        print(record[2]) 
        print(record[3])
        print('')

如果抛出任何异常,它将自动回滚。

如果出现任何问题,请添加重定向

DB::transaction(function () use ($database, $available) {
    for ($i=0; $i < 3; $i++) {
      if($available < 3){
        echo 'success';
        $database->save();
      }else{
        echo 'error';
        throw new \Exception('Error');
      }
    }
});