我试图生成一堆同名的输入,并将其保存到sql表中。我遇到的问题是,我的代码适用于大约4个输入,其余的都没有发生。
生成输入的代码:
for ($x = 0; $x < 10; $x++) {
echo " ID: <input name=\"IDadd[]\" type=\"text\"> \n";
echo " Name: <input name=\"Nameadd[]\" type=\"text\"> \n";
echo " Job: <select name='Jobadd[]'>\n";
echo " <option value='Tech'>Tech</option>\n";
echo " <option value='Check-In'>Check-In</option>\n";
echo " <option value='Inventory'>Inventory</option>\n";
echo " <option value='Beats'>Beats</option>\n";
echo " <option value='Computers'>Computers</option>\n";
echo " <option value='IOS'>IOS</option>\n";
echo " <option value='Remarketing'>Remarketing</option>\n";
echo " </select> \n";
echo "<br><br>";
}
应将其整理并保存的代码:
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">';
}
}
- 编辑
那么这应该适用吗?
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">';
}
}
}
答案 0 :(得分:0)
您的问题是foreach
正在遍历$_POST['IDadd']
,$_POST['Nameadd']
和$_POST['Jobadd']
,而不是这些数组的内容。只需查看$key
。
您需要做的是确保它们不是空的,然后遍历内容:
// I'm just showing checking all the arrays aren't empty
// you'll also want to check if they have the same length
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]);
// ...
}
}
您还应该考虑使用预准备语句来减少SQL注入的可能性。