I am trying to post data into my database from these while loop. It helps me get the monthly periods within a particular range. I want to pick the dates and input the dates into my database along with additional data. I am stuck, please go easy on me.
// Calculate interest $intrest_loan = $loan_amount * $intrest / 100; $monthly_payment = $loan_amount / $tenor; // echo $intrest_loan; // echo $monthly_payment; $date = $start; while ($date <= $end) { $date = date('Y-m-d', strtotime($date . ' +1 month')); // echo $date . "n"; $sql = "insert into collection (period, amount_collected) values ($date, $monthly_payment)"; $resultn = mysqli_query($connection, $sql); if($resultn) { }else{ echo "<p>Failed to load collections</p>"; } }
Edited code.
Advertisement
Answer
Assuming that you are using mysqli
then I hope this might help. In keeping with comments made regarding the 2 disconnected loops you can/should combine into a single loop where the date value is calculated and used as input for the sql statement. As you posted a snippet of code rather than the full thing it is impossible to say if your sql is vulnerable to sql injection or not but where money is involved it would be wise to take no chances and try to mitigate against malicious attacks – thus use a prepared statement.
The DateTime
class has a variety of methods to help manipulate the date and in this case the addition of a month can be done very cleanly as shown below.
In essence you create the sql statement with placeholders (?
) and bind those placeholders to variables at runtime. Once the statement is prepared it can be executed as many times as required with little extra overhead.
/* some example / dummy dates ~ source unknown */ $str_date_start='2020-01-01'; $str_date_end='2021-01-01'; /* create a prepared statement */ $sql='insert into `collection` ( `period`, `amount_collected` ) values (?,?)'; $stmt=$conn->prepare( $sql ); $stmt->bind_param( 'ss', $date, $monthly_payment ); /* original repayment calculations - corrected spelling of interest*/ $interest_loan = $loan_amount * $interest / 100; $monthly_payment = $loan_amount / $tenor; /* create new date objects */ $start=new DateTime( $str_date_start ); $end=new DateTime( $str_date_end ); $interval=new DateInterval('P1M'); /* make sure we start AT the start */ $start->sub( $interval ); while( $start < $end ){ $start->add( $interval ); $date=$start->format('Y-m-d 00:00:00'); $stmt->execute(); } $stmt->close(); $conn->close();