提问人:Concentric 提问时间:12/27/2018 最后编辑:Brian Tompsett - 汤莱恩Concentric 更新时间:12/27/2018 访问量:338
计算要添加和插入到表格中的行数
Counting Rows to be added and insert into table
问:
我有一个脚本,允许在页面上创建多行,然后我需要在帖子上计算行数,然后将每一行插入到表格中。
我有 GUI 工作,用户可以根据需要添加或删除行,但当我提交时没有数据写入表。我尝试将帖子的脚本更改为直接“$variables”,它可以写,但只写第一行。
我已经附上了我正在使用的动作脚本 WebLesson,它适用于一个领域,但对于多个领域,我不知该尝试什么。
//includes
include '----';
include '---';
session_start();
$number = count($_POST['name']);
echo $_POST['name'] . "<br>";
echo $number . "<br>";
if($number >= 1)
{
echo $_POST['pasid'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
$id = $_POST['pasid'];
$name = $_POST['name'];
$dose = $_POST['dose'];
$dir = $_POST['directions'];
$time = $_POST['time'];
echo $i;
for($i=0; $i<$number; $i++)
{
if(trim($_POST["name"][$i] != ''))
{
$sql = "INSERT INTO meds (id, name, dose, directions)
VALUES('".mysqli_real_escape_string($_POST["pasid"][$i])."',
'".mysqli_real_escape_string($_POST["name"][$i])."',
'".mysqli_real_escape_string($_POST["dose"][$i])."',
'".mysqli_real_escape_string($_POST["directions"][$i])."',
'".mysqli_real_escape_string($_POST["time"][$i])."') " ;
mysqli_query($conn, $sql);
}
}
echo "Data Inserted";
}
else
{
die("Connection failed: " . mysqli_connect_error());
}
我希望它计算发布了多少行,然后将每一行提交到表格中。
UI图片:
答:
0赞
Parsonswy
12/27/2018
#1
您可以为每个表单元素生成唯一的属性,然后在 PHP 中遍历它们。最简单的方法可能是在每次用户创建新行时在属性末尾递增一个数字。您将不得不使用 Javascript 来做到这一点。name
name
var suffix = 0;
function addNewRow(){
...
<input type="text" name="pasid_${i}"/> //Add incriminating suffix
...
suffix++; //Increment suffix for next time
}
那么你的PHP就会看起来像
$suffix = 0;
while(isset($_POST['pasid' . $suffix])){ //Keep looping until no more POST value
//Process row $suffix, referencing all the data like $_POST['field_name'. $suffix]
$suffix++; //Increment suffix for the next field
}
确保您在 while 循环中检查的字段是必需的,否则用户可能会省略输入,并且循环会过早终止。如果非必需字段,还可以在 while 循环中检查多个索引。$_POST
评论