PHP не работает при обработке больших запросов - PullRequest
0 голосов
/ 05 мая 2018

Я создаю интернет-магазин с использованием PHP, который обрабатывает более 200 000 запросов одновременно, но я получаю дублированные значения в своей базе данных и отрицательные значения.

enter image description here

Снимок экрана выше - единственное условие, которое проверяет, достаточно ли у пользователя денег на его счете. Но я получаю следующие результаты ниже

Simulation result from database

Я прикрепил код здесь

<?php

require 'db.php';
use Illuminate\Database\Capsule\Manager as DB;

index();

function index()
{
    ini_set('max_execution_time', 3000);
    $members = DB::table("tempcurrentamount")->get();

    $products = DB::table('product')->get();

    $tmp_items = [];

    foreach ($products as $product) {
        array_push($tmp_items, $product->id);
    }

    foreach ($members as $member) {
        // GENERATE RANDOM ITEMS AND QUANTITY
        $items = [];
        $qty = [];

        for ($i=0; $i < 5; $i++) {
            array_push($qty, rand(1,20));
        }

        for ($i=0; $i < 5; $i++) {
            array_push($items, array_rand(array_flip($tmp_items), 1));
        }

        submitRequest($member->id, $qty, $items);
    }
}

function submitRequest($id, $qty, $items)
{
    $user_id = $id;

    $account = DB::table('tempcurrentamount')->where('id', $user_id)->first();

    $date_created= date('Y-m-d');
    $product_id = $items;
    $quantity = $qty;
    $total_amount = 0.0;
    $amount = [];

    // if($user_stage == 0){
    //     return json_encode("SORRY, You can not order for any product in Stage 0.");
    // }

    // Get Amount of each products
    for ($i=0; $i < count($product_id); $i++) { 

            $product_price = DB::table('product')->where('id', $product_id[$i])->first()->price;
            $total_amount += $product_price * $quantity[$i];

        //Store product prices in an array
        array_push($amount, ($product_price / 200));
    }

    // BEGIN TRANSACTION
    echo $id . "Total Amount: " . $total_amount ." Account Balance: ". (($account->foodcash + $account->payoutcash) * 200) . "<br>";

    if ($total_amount < (($account->foodcash + $account->payoutcash) * 200)) {

        processPayment($total_amount, $account, $user_id, $product_id, $date_created, $quantity, $amount);

        echo $id . " Successful<br><br>";     
        return;
    }else{
        echo $id . " Failed Insufficient Balance<br><br>";     
        return;
    }
}

function processPayment($total_amount, $account, $user_id, $product_id, $date_created, $quantity, $amount)
{

    DB::beginTransaction();

    try {

        //Convert Total Amount To The MLM System rate
        $order_amount_in_system_rate = $total_amount / 200;

        //Deduct Amount From table tempcurrentamount
        #===================================================================================
      //Check If Amount is greater than foodcash
        $deductFromPayCash = 0;

        if($order_amount_in_system_rate > $account->foodcash){
            $deductFromPayCash = $order_amount_in_system_rate - $account->foodcash;
        }

      //Perform Deduction
        if($deductFromPayCash > 0 && $account->payoutcash > 0){

            DB::table('tempcurrentamount')
            ->where('id', '=', $user_id)
            ->decrement('foodcash', $account->foodcash);

            DB::table('tempcurrentamount')
            ->where('id', '=', $user_id)
            ->decrement('payoutcash', $deductFromPayCash);
        }else{
            DB::table('tempcurrentamount')
            ->where('id', '=', $user_id)
            ->decrement('foodcash', $order_amount_in_system_rate);
        }
        #===================================================================================

        //If Decrement Fails, ROLLBACK TRANSACTION

        //Add Items to table mlm_foodcollection
        for ($i=0; $i < count($product_id); $i++) {

            //Check if Product is empty  
            if($product_id[$i] == 0){
                continue;
            }

            //Insert Info into mlm_foodcollection table
            DB::table('itemsordered')->insert([
                'user_id' => $user_id,
                'group_leader_id' => rand(1,10),
                'product_id' => $product_id[$i],
                'quantity' => $quantity[$i],
                'amount' => $amount[$i],
                'date_created' => $date_created,
                ]);
        }

        //Log collected item To table mlm_goodscollectionlog
        DB::table('log')->insert([
            'user_id' => $user_id,
            'prev_amount' => $account->foodcash + $account->payoutcash,
            'amount_deducted' => $order_amount_in_system_rate,
            'trans_date' => date('Y-m-d h:i:s'),
            ]);

        // IF NOT QUERY FAILS, COMMIT TRANSACTION
        DB::commit();

        echo $user_id . " Successful<br>";     
        return;

        // all good
    } catch (\Exception $e) {
        DB::rollback();
        echo $user_id . "Something went wrong<br>";     
        return;
    }
}

Спасибо, ребята

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...