I'm attempting to generate a bunch of inputs of the same name, and saving it to an sql table. The issue i'm having is, my code works for about 4 of the inputs, then the rest nothing happens.
Code thats generating the inputs:
for ($x = 0; $x < 10; $x++) {
echo " ID: <input name=\"IDadd[]\" type=\"text\">
";
echo " Name: <input name=\"Nameadd[]\" type=\"text\">
";
echo " Job: <select name='Jobadd[]'>
";
echo " <option value='Tech'>Tech</option>
";
echo " <option value='Check-In'>Check-In</option>
";
echo " <option value='Inventory'>Inventory</option>
";
echo " <option value='Beats'>Beats</option>
";
echo " <option value='Computers'>Computers</option>
";
echo " <option value='IOS'>IOS</option>
";
echo " <option value='Remarketing'>Remarketing</option>
";
echo " </select>
";
echo "<br><br>";
}
Code that should be sorting it out and saving it:
if ( isset( $_POST[ 'newEmployee' ] ) )
{
$index = 0;
foreach ($_POST as $key => $value){
$userId = $_POST['IDadd'][$index];
$userName = $_POST['Nameadd'][$index];
if (empty($_POST['Nameadd'][$index])) {
return;
}
$userJob = $_POST['Jobadd'][$index];
$index++;
$sql = "INSERT INTO Employee (userId, Name, Job, Week)
VALUES ('$userId', '$userName', '$userJob', '$currentWeekIs')";
mysqli_query($con, $sql);
}
if($sql) // will return true if succefull else it will return false
{
mysqli_close( $con );
sleep(4);
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=add.php">';
}
}
--EDIT
So this should work then?
if ( isset( $_POST[ 'newEmployee' ] ) )
{
if (!empty($_POST['IDadd'])) {
// loop through the keys of one of the arrays
foreach (array_keys($_POST['IDadd']) as $index) {
$userId = mysqli_real_escape_string($_POST['IDadd'][$index]);
$userName = mysqli_real_escape_string($_POST['Nameadd'][$index]);
$userJob = mysqli_real_escape_string($_POST['Jobadd'][$index]);
$sql = "INSERT INTO Employee (userId, Name, Job, Week)
VALUES ('$userId', '$userName', '$userJob', '$currentWeekIs')";
mysqli_query($con, $sql);
}
if($sql) // will return true if succefull else it will return false
{
mysqli_close( $con );
sleep(4);
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=add.php">';
}
}
}