I am having an issue. I have a bunch of inputs that share the same name. This creates arrays which are placed into the database and that all works fine but I am having a major dilemma in trying to keep the blank rows of inputs from creating blank entries in the database table.
The code is as such:
foreach($_POST['datetime'] as $dbrow=>$startdate) {
if(isset($_POST['def'])) {
$start = $startdate;
$abc = $_POST['abc'][$dbrow];
$def = $_POST['def'][$dbrow];
$ghi = $_POST['ghi'][$dbrow];
$db_insert = "INSERT INTO tablename (start, abc, def, ghi) VALUES('$start', '$abc', '$def', '$ghi')";
This is fine and dandy but I cant get the if statement to work. The form that is using POST to get the users information has 5 rows of inputs each with fours columns (start, abc, def, ghi). If I enter data in the form and submit it, then all the data goes to the database (yay - success), if I only enter the data in rows 1-4 then the database still enters 5 rows of data. What am I doing wrong?
---------------------EDIT--------------------- Ok so upon a deeper look what appears to be happening is the code keeps wanting to submit ALL of rows of dynamically generated inputs whether they contain content or not. So I devised the following code:
$db_tur = count(array_filter($start_date));
for($db_total_used_rows=0;$db_total_used_rows<=$db_tur;$db_total_used_rows++){
$db_start_date = $_POST['datetime'][$db_total_used_rows];
$db_abc = $_POST['abc'][$db_total_used_rows];
$db_def = $_POST['def'][$db_total_used_rows];
$db_ghi = $_POST['ghi'][$db_total_used_rows];
}
$db_insert = .....;
In theory what this does is $db_tur counts up all of the inputs being used under the start_date variable. I then break it into a count array which should be able to be used as $db_total_used_rows. However this doesnt seem to be limiting the total number of rows of inputs being inserted into the database. So I guess its back to the drawing board unless someone else has a better idea of how to accomplish this. I'm so ready to give up right now.
Use this loop structure:
foreach ($_POST['datetime'] as $dbrow => $start) {
$abc = $_POST['abc'][$dbrow];
$def = $_POST['def'][$dbrow];
$ghi = $_POST['ghi'][$dbrow];
if (!empty($abc) && !empty($def) && !empty($ghi) && !empty($start)) {
$db_insert = ...;
...
}
}
You could change &&
to ||
if it's OK for the user to leave some of the fields blank -- it will only skip rows where all fields are blank.