计算要添加和插入到表格中的行数

Counting Rows to be added and insert into table

提问人:Concentric 提问时间:12/27/2018 最后编辑:Brian Tompsett - 汤莱恩Concentric 更新时间:12/27/2018 访问量:338

问:

我有一个脚本,允许在页面上创建多行,然后我需要在帖子上计算行数,然后将每一行插入到表格中。

我有 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图片:

enter image description here

php mysqli 计数 插入

评论

0赞 Concentric 12/27/2018
“_ POST”是根据 Web 课程列出的模板,我遵循了它。我更愿意使用我上面定义的变量
0赞 thinsoldier 12/27/2018
stackoverflow.com/questions/22304930/......请阅读对该问题的答复。请勿以使用方式使用mysqli_real_escape_string。它并不像你所相信的那样安全。
0赞 thinsoldier 12/27/2018
如果你能发布你的UI的屏幕截图,我可能会更好地理解你的问题。我最好的猜测是使用数组和 foreach 将导致更容易遵循适合您情况的代码。对于php初学者,我建议在 phpdelusions.net 上阅读有关PDO和MySQLi的所有细节,但实际上不要将PDO和MySQLi用于任何易于使用的库(如 j4mie.github.io/idiormandparis)轻松处理的内容

答:

0赞 Parsonswy 12/27/2018 #1

您可以为每个表单元素生成唯一的属性,然后在 PHP 中遍历它们。最简单的方法可能是在每次用户创建新行时在属性末尾递增一个数字。您将不得不使用 Javascript 来做到这一点。namename

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