skip to Main Content

Im writing a PHP scirpt that generates car orders of a random number until it reaches the max car order limit. The code works well on the first run but subsiqent runs it generates more cars than the max allowed. Generally about double of what i need, i’ve be been trying to figure this out for a while now but it keeps coming up with the same results. Below is the code

foreach ($industries as $industry) {
    $indyId = $industry['id'];
    $cars = getIndyCars($conn, $indyId);
    //$lastOrderNumber = getLastOrderNumber($conn, $indyId);
    $orderNumber = generateOrderNumber($conn, $indyId);
    $industryOrders = [];

    foreach ($cars as $car) {

        $id = $car['id'];
        $maxCars = $car['maxCars'];
        $loaded = $car['loaded'];
        $x = 1;
        $typeId = $car['carType'];
        $carsAlreadyOrdered = getCarsOrderd($conn, $id);
        /*
        * CARS ARE ORDERED ON A RANDOM SCALE BETWWEN THE MAX CARS AND CARS ALREADY ORDERED THEY WILL KEEP ORDERING BETWEEN THE AMOUNT OF CARS LEFT AND THE MAX CARS
        * EVENTUALLY ORDERES WILL BE PLACED ON A SCHEDULE BUT THAT WILL COME LATER. 
        */
        if ($carsAlreadyOrdered < $maxCars) {
        $remainingCars = $maxCars - $carsAlreadyOrdered;
        $remainingCars -= $carsOrdered;
        $carsOrdered = rand(0, $remainingCars);
        
if ($carsOrdered + $remainingCars > $maxCars) {
            $carsOrdered = 0;
        }
        $carOrders = [];
        

        echo '<b>' . $carsOrdered . ' Cars ordered for '.$id.'</b> '.$remainingCars.' left<br>';
        if ($carsOrdered !== 0) {
            $carsOrdered = $carsAlreadyOrdered + $carsOrdered;
            updateCarsOrdered($conn, $id, $carsOrdered);
        }else{
        updateCarsOrdered($conn, $id, $carsOrdered);
        }
        $filterCars = getLocalFilterCars($conn, $typeId, $indyId);

        if (is_array($filterCars) && count($filterCars) > 0) {
            echo "<td>";
            for ($x = 0; $x < $carsOrdered; $x++) {
                $randomCarIndex = mt_rand(0, count($filterCars) - 1);
                $randomCar = $filterCars[$randomCarIndex];
                //echo $randomCar['filteredCars'];
                $carId=$randomCar['filteredCars'];
                $carWeight = 0;

                if ($loaded == 1) {
                    $payload = getCarPayload($cdbconn, $randomCar['filteredCars']);
                    $carLoad = rand(1, $payload);
                    $carWeight = $carLoad;
                    $totalLoadWgt = (int)$totalLoadWgt + (int)$carLoad;
                } elseif ($loaded == 0) {
                    $tareWeight = getCarEmptyWeight($cdbconn, $randomCar['filteredCars']);
                    $carWeight = $tareWeight;
                    $totalEmptyWeight = (int)$totalEmptyWeight + (int)$tareWeight;
                }
                addOrder($conn, $orderNumber, $indyId, $id, $carId, $loaded, $carWeight);
               /* $carOrders[] = [
                    'car' => $randomCar['filteredCars'],
                    'loaded' => $loaded,
                    'payload' => $carWeight
                ];*/
            }
        }

/*        if (!empty($carOrders)) {
            $industryOrders[] = [
                'industryTypeId' => $id,
                'orders' => $carOrders
            ];
        }*/
    }//IF MAX CARS ORDERED
    else{
        echo "No cars ordered for".$id."<br>";
    }

    }//CarForeach*/

    if (!empty($industryOrders)) {
        ///$jsonIndustryOrders = json_encode($industryOrders);
        //addOrder($conn, $indyId, $id, $carId, $loaded, $carWeight);
        //addOrder($conn, $indyId, $jsonIndustryOrders);
    }
}

Functions – The first function gets the current car count from the database and the secound updates the car cound hen the order is generated.

function getCarsOrderd($conn, $indyId){
$sql = "SELECT * FROM industry_cars WHERE id =?;";
    $stmt = mysqli_stmt_init($conn);
 if (!mysqli_stmt_prepare($stmt, $sql)) {
    header("location: details.php?error=stmtfailed");
        exit();
 }
    mysqli_stmt_bind_param($stmt, "s", $indyId);
    mysqli_stmt_execute($stmt);

    $resultData = mysqli_stmt_get_result($stmt);
    if ($row = mysqli_fetch_assoc($resultData)){
        return $row['carsOrdered'];
    }else{
        $result = false;
        return $result;
}
}
function updateCarsOrdered($conn, $indyId, $carsOrdered){
        $sql = "UPDATE industry_cars SET carsOrdered = ? WHERE id=?;";
    $stmt = mysqli_stmt_init($conn);
 if (!mysqli_stmt_prepare($stmt, $sql)) {
    header("location: ../details.php?error=stmtfailed");//ssssss
        exit();
 }
    mysqli_stmt_bind_param($stmt, "ss", $carsOrdered, $indyId);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
}
function getIndustryOrders($conn, $indyId){
    $sql = "SELECT * FROM industryorders WHERE industryId = ?;";
    $stmt = mysqli_stmt_init($conn);
 if (!mysqli_stmt_prepare($stmt, $sql)) {
    header("location: details.php?error=stmtfailed");
        exit();
 }
 mysqli_stmt_bind_param($stmt, "s", $indyId);
    mysqli_stmt_execute($stmt);

    $resultData = mysqli_stmt_get_result($stmt);

    while ($result = mysqli_fetch_all($resultData, MYSQLI_ASSOC)) {
        return $result;
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    I was able to find a solution to my issue I added some notes within the code. I believe it was an issue with the $carsOrdered variable being used to calculate the number of cars ordered and adding it on to the running total. I replaced that with $runningCarsTotal which seemed to fix this issue.

    $region_id = 1;
    $totalLoadWgt = "";
    $totalEmptyWeight = "";
    
    $industries = getIndustryList($conn, $region_id);
    
    foreach ($industries as $industry) {
        $indyId = $industry['id'];
        $industry['industryName'];
        $cars = getIndyCars($conn, $indyId);
        $orderNumber = generateOrderNumber($conn, $indyId);
        echo "<tr><td colspan='4'>";
        echo $industry['industryName'];
        
        foreach ($cars as $car){
    
                $id = $car['id'];
                $maxCars = $car['maxCars'];
                $loaded = $car['loaded'];
                $x = 1;
                $typeId = $car['carType'];
             
                $carsAlreadyOrdered = getCarsOrderd($conn, $id); // Gets number of cars that have already been ordered
              
                $remainingCars = $maxCars - $carsAlreadyOrdered; // Calcualtes how many cars remain after previous order
            if ($carsAlreadyOrdered <= $maxCars) {
                $carsOrdered = rand(0, $remainingCars);
              
                $runningCarsTotal = $carsAlreadyOrdered+$carsOrdered; // Adds number of cars ordered to the running total
                updateCarsOrdered($conn, $id, $runningCarsTotal); // Updates database with new car count
            }
                $filterCars = getLocalFilterCars($conn, $typeId, $indyId);
            if (is_array($filterCars) && count($filterCars) > 0) {
                    for ($x = 0; $x < $carsOrdered; $x++) {
                    $randomCarIndex = mt_rand(0, count($filterCars) - 1);
                    $randomCar = $filterCars[$randomCarIndex];
                    $carId=$randomCar['filteredCars'];
                    $carWeight = 0;
    
                    if ($loaded == 1) {
                        $payload = getCarPayload($cdbconn, $randomCar['filteredCars']);
                        $carLoad = rand(1, $payload);
                        $carWeight = $carLoad;
                        $totalLoadWgt = (int)$totalLoadWgt + (int)$carLoad;
                    } elseif ($loaded == 0) {
                        $tareWeight = getCarEmptyWeight($cdbconn, $randomCar['filteredCars']);
                        $carWeight = $tareWeight;
                        $totalEmptyWeight = (int)$totalEmptyWeight + (int)$tareWeight;
                    }
    
                    addOrder($conn, $orderNumber, $indyId, $id, $carId, $loaded, $carWeight); // Adds data to database with the above data added. 
                    }
            }           
        }
    }
    

  2. Since you are applying some sort of logic, generating a random number of cars, but you’re not stablishing a limit, you can try to use a for loop with a random probability set, to ensure you’ll have a limit, and a more realistic behavior.

    Let’s then change the logic, you can try this approach instead:

    foreach ($cars as $car) {
        $id = $car['id'];
        $maxCars = $car['maxCars'];
        $loaded = $car['loaded'];
        $x = 1;
        $typeId = $car['carType'];
        $carsAlreadyOrdered = getCarsOrderd($conn, $id);
    
    
        if ($carsAlreadyOrdered < $maxCars) {
        $remainingCars = $maxCars - $carsAlreadyOrdered;
        $carsOrdered = rand(0, $remainingCars);
        if ($carsAlreadyOrdered < $maxCars) {
            $remainingCars = $maxCars - $carsAlreadyOrdered;
            $probability = rand(0, 100) / 100; // Set a random probability
            
            for ($i = 0; $i < $remainingCars; $i++) {
                if (rand(0, 100) / 100 < $probability) { // So, if the number is lees than the probability, +1 car
                    $carsAlreadyOrdered++;
                    updateCarsOrdered($conn, $id, $carsAlreadyOrdered);
                } else { // If more than the probability, stop.
                    break;
                }
            }
    
            echo '<b>' . $carsAlreadyOrdered . ' Cars ordered for '.$id.'</b> '.$remainingCars.' left<br>';
            $filterCars = getLocalFilterCars($conn, $typeId, $indyId);
    
            if (is_array($filterCars) && count($filterCars) > 0) {
                echo "<td>";
                for ($x = 0; $x < $carsOrdered; $x++) {
                    $randomCarIndex = mt_rand(0, count($filterCars) - 1);
                    $randomCar = $filterCars[$randomCarIndex];
                    //echo $randomCar['filteredCars'];
                    $carId = $randomCar['filteredCars'];
                    $carWeight = 0;
    
                    if ($loaded == 1) {
                        $payload = getCarPayload($cdbconn, $randomCar['filteredCars']);
                        $carLoad = rand(1, $payload);
                        $carWeight = $carLoad;
                        $totalLoadWgt = (int)$totalLoadWgt + (int)$carLoad;
                    } elseif ($loaded == 0) {
                        $tareWeight = getCarEmptyWeight($cdbconn, $randomCar['filteredCars']);
                        $carWeight = $tareWeight;
                        $totalEmptyWeight = (int)$totalEmptyWeight + (int)$tareWeight;
                    }
                    addOrder($conn, $orderNumber, $indyId, $id, $carId, $loaded, $carWeight);
                    /* $carOrders[] = [
                        'car' => $randomCar['filteredCars'],
                        'loaded' => $loaded,
                        'payload' => $carWeight
                        ]; */
                }
            }
            
                /*if (!empty($carOrders)) {
                        $industryOrders[] = [
                        'industryTypeId' => $id,
                        'orders' => $carOrders
                        ];
                    } */
        } //IF MAX CARS ORDERED
        else {
            echo "No cars ordered for" . $id . "<br>";
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search