我有一份表格,询问有关工作的一些基本问题,然后要求进入的人列出当时与他们在一起的所有同事。我想要做的是让所有在场的同事都输入一行数据 - 所以其他所有细节都保持不变,除了他们的work_id(这是人的标识符)。我的代码似乎向db提交了1行,其中workID字段为空
<?php
require_once('includes/dbconnect.php');
$varWorkID = $_POST['workid'];
$varDate = $_POST['date'];
$varType = $_POST['type'];
$varSuper = $_POST['supervisor'];
$varReference = $_POST['reference'];
//Remove last part of array as extra 1 sent through by form
$workID = array_pop($varWorkID);
for ($i=0; $i < count($workID); $i++ )
{
mysqli_query($conn,"INSERT INTO searches (workid,date,type,super,reference) VALUES('".$workID."','".$varDate."','".$varType."','".$varSuper."','".$varReference."')");
}
echo "Completed";
我认为我相当接近,但我只需要为每个在职员工填写workid以填充每个工作ID。
非常感谢任何帮助
答案 0 :(得分:1)
这里的问题是你在进入循环$workID = array_pop($varWorkID);
之前调用for ($i=0; $i < count($workID); $i++ )
,所以PHP解释器认为你只想迭代那个元素的长度。你真正想要做的是在循环内部时从阵列中弹出一个元素。
<?php
require_once('includes/dbconnect.php');
$varWorkID = $_POST['workid'];
$varDate = $_POST['date'];
$varType = $_POST['type'];
$varSuper = $_POST['supervisor'];
$varReference = $_POST['reference'];
// iterate over the count of the whole array $varWorkID = $_POST['workid']
for ($i=0; $i < count($varWorkID); $i++ )
{
// now pop off the array inside the loop
//Remove last part of array as extra 1 sent through by form
$workID = array_pop($varWorkID);
mysqli_query($conn,"INSERT INTO searches (workid,date,type,super,reference) VALUES('".$workID."','".$varDate."','".$varType."','".$varSuper."','".$varReference."')");
}
echo "Completed";
现在我认为@Dima Fitiskin's comment提出了一个更好的方法,因为你并不需要花费多少时间来调用另一个函数array_pop
或者在堆栈$workID
上抛出另一个变量&# 39;已经有了循环内的索引$i
的迭代引用。
<?php
require_once('includes/dbconnect.php');
$varWorkID = $_POST['workid'];
$varDate = $_POST['date'];
$varType = $_POST['type'];
$varSuper = $_POST['supervisor'];
$varReference = $_POST['reference'];
// iterate over the count of the whole array $varWorkID = $_POST['workid']
for ($i=0; $i < count($varWorkID); $i++ )
{
mysqli_query($conn,"INSERT INTO searches (workid,date,type,super,reference) VALUES('".$varWorkID[$i]."','".$varDate."','".$varType."','".$varSuper."','".$varReference."')");
}
echo "Completed";