Skip to content
Advertisement

Loop runs until the condition is met but insert statement is being used only once

I am trying to create an Expense Management system where I will be able to schedule future expenses if the user selects frequency like daily, weekly, monthly etc.

To achieve this, I have created a loop but in the code above, My loop runs, and $sde is echoed as desired but my insert statement runs only once. I want to run the insert statement for every updated date.

$sde=$arr['startdateexpense'];
$ede=$arr['enddateexpense'];
$modifiers=[
"Annually"=>"+1 year",
"Daily"=>"+1 day",
"Weekly"=>"+1 week",
"Fort-nightly"=>"+2 weeks",
"Monthly"=>"+1 month",
"Quarterly"=>"+4 months",
"Semi-Annually"=>"+6 months",
                ];
while($sde <= $ede){
echo $sde , ' ';
$modifier= $modifiers[$ExpenseFrequency];
$sde = new DateTime($sde);
$sde->modify($modifier);
$sde= $sde->format('Y-m-d');                
//Insert statement
$sql = "INSERT INTO expense (ExpenseDate, ExpenseCategoryName, ExpenseItem, ExpenseCost, Image, ExpenseDescription) VALUE ('".$sde."','".$ExpenseCategoryID."', '".$item."', 
             '".$costitem."', '".$tphoto."', '".$description."')";
    }

My $sde is updated every time but the only problem is with the insert statement.

Can anyone please help me with this?

Advertisement

Answer

You keep setting $sql inside the loop, it ends up with the value of the last iteration.

Need to collect sets of values and then insert. Also its VALUES not VALUE.

$values = array();

while($sde <= $ede){
    echo $sde , ' ';
    $modifier= $modifiers[$ExpenseFrequency];
    $sde = new DateTime($sde);
    $sde->modify($modifier);
    $sde= $sde->format('Y-m-d');                
    //Insert statement
    $values[] = "('".$sde."','".$ExpenseCategoryID."', '".$item."', '".$costitem."', '".$tphoto."', '".$description."')";
}

$sql = "INSERT INTO expense (ExpenseDate, ExpenseCategoryName, ExpenseItem, ExpenseCost, Image, ExpenseDescription) VALUES " . join(', ', $values);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement