dongsi4547 2016-07-03 04:18
浏览 54
已采纳

PHP中的Foreach循环 - 全部或全部

In a foreach loop, say I wanted to do the following

foreach($items as $item)
{

  // charge a user for purchasing an item - IS BEING DONE THROUGH AN API CALL WITH STRIPE
  // ie: \Stripe\Charge::create(...);

  // save some info to a database
  // using Laravel for this project so this is within a DB::transaction(...);


  // send a notification email to the buyer
  // Emails are being queued to avoid slowing down the request
  // ie: Mail::queue(...);
}

I would like an all or nothing situation to occur. For example, if an error occurs during the iteration, then NONE of the items are charged, no information is saved to the database, and the buyer does not get a notification email. However, if the foreach loop successfully iterates over each item, then charge the user, save info to database, and send notification email. How do I do this?

  • 写回答

4条回答 默认 最新

  • dsoxcj7276 2016-07-03 04:57
    关注

    I would recommend using Transactions and notifying the buyer at the end.

    Mysqli Example:

    $dbConn->begin_transaction();
    
    try{
    
        foreach($ítems as $item){
            //Whatever you are going to do
        }
    
        if($dbConn->commit()){
    
        //Notify buyer about all the transactions, the user doesn't receives the notification unless the commit was succesful
    
       }
    
    catch(Exception ex){
        $dbConn->rollback();
    }
    

    Additionally you could verify the return values of the mysqli functions, I Just wanted to focus on the transaction use.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!