I am only starting with PHP so please bear with me. I have a seemingly easy assignment which I've stuck with. I have tried to search for some help but couldn't really find what I need exactly. And what I need to do, is to insert multiple records to mysqli table from an HTML form based on selected number of records and selected date.
It is a sort of recurring event but without any calendars or server side events. Just inserting new records into an existing table.
I have created the form which looks like:
<form action="" method="post" id="form_pay" name="form_pay" >
<input type="text" name="pay_client_id[]" value="<?php echo $client_id; ?>" />
<input type="text" name="pay_amount[]" />
<input type="text" name="pay_number[]" />
<input type="text" name="pay_due_date[]" />
<input type="submit" id="submit_pay" name="submit_pay" value="Create Table" />
</form>
and DB Table called pay_schedules:
=====================================================
pay_id | client_id | amount | due_date
=====================================================
and finally beginning of php:
if(isset($_POST["submit_pay"])){
$client_id = $_POST['pay_client_id'];
$amount = $_POST['pay_amount'];
$due_date = date('Y-m-d',strtotime($_POST['pay_due_date']));
$pay_number = $_POST['pay_number'];
//connection details
$servername = "localhost";
$username = "my_user";
$password = "my_password";
$dbname = "my_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
// insert into table
$sql = "INSERT INTO pay_schedules
(client_id, amount, due_date)
VALUES ( '$client_id', '$amount', '$due_date' ) ";
// messages
if ($conn->query($sql) === TRUE) { } else { $conn->error; }
$conn->close();
}
Obviously PHP is not complete and I know I have to wrap the query in a loop but I am facing following problems:
- how to insert number of records based on pay_number field (e.g. 4 records, 10 records, 24 records ect)
- how to create foreach loop that increase month +1 with each inserted record up to the number of selected pay_number field
- all inserted records have to start with due_date and have the same day but consecutive month (e.g. 2019-11-20, 2019-12-20, 2020-01-20), but how to avoid a problem with last day of month if 28th, 29th 30th or 31st is selected for months without those days?
so what I actually want to achieve is a table that looks like below based on following assumptions:
- pay_client_id: 1001
- pay_number: 5
- pay_amount: 150.25
- pay_due_date: 2019-10-31
- pay_id: auto increment PK
final table:
=====================================================
pay_id | client_id | amount | due_date
=====================================================
1 | 1001 | 150.00 | 2019-10-31
2 | 1001 | 150.00 | 2019-11-30
3 | 1001 | 150.00 | 2019-12-31
4 | 1001 | 150.00 | 2020-01-31
5 | 1001 | 150.00 | 2020-02-29
I hope I explained my problem so if anyone could help me here I would greatly appreciate it.