我有一个动态 HTML 表格,允许用户通过单击按钮添加行。每行的数据都需要插入到我使用 PHP 脚本的 MySQL 表中。现在,由于每次 HTML 表中的行数可能不同,我该如何在 PHP 中处理这个问题。一种方法是计算 HTML 表中的行数(我在某处发现可以这样做)
$rows = $table->find('#studenttable'); /*line 4 of my code*/
$count = count($rows); /*studenttable is the id of my table*/
echo $count;
然后运行一个 for 循环来为每一行插入数据。但这是一个 fatal error 。
注意: undefined variable :第 4 行 savedata.php 中的表
fatal error :在第 4 行的 savedata.php 中对非对象调用成员函数 find()
另一种方法可能是使用 foreach 循环,我完全不知道在这种情况下如何实现。
此代码动态添加新行
var count=2;
function addRow()
{
var table=document.getElementById("studenttable");
var row=table.insertRow(-1);
var cell15=row.insertCell(14);
var ipt8 = document.createElement('input');
ipt8.setAttribute("type", "hidden");
ipt8.name = "htmlrow[]";
ipt8.value = count;
cell15.appendChild(ipt8);
count++;
}
获取行数的PHP文件
<?php
$arr = $_POST['htmlrow'];
foreach ($arr as $val) {
$count= $val;
echo $count;
}
?>
仍然没有得到结果。
最佳答案
您不能在 PHP 中直接访问 HTML 元素。
我的建议是更改客户端代码,以便每当向表中添加一行时,<input type="hidden" value="value-of-that-row" name="htmlrow[]"/>
被添加到表单中。
这样,当提交表单时(您将整个表单包裹在表单中,对吧?)您可以使用 $_POST['htmlrow']
访问处理表单的 PHP 中生成的表行。 ,现在将包含一个用户数据数组。
关于php - 使用php计算html表中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17497606/