2013-07-05 48 views
3

我有一個動態HTML表格,允許用戶在單擊按鈕時添加行。來自每行的數據需要插入MySQL表格中,我使用PHP腳本。現在,因爲每次HTML表格中的行數可能不同,我該如何在PHP中處理這個問題。一種方法是計算在HTML錶行(這是我發現的地方是這樣做)的數量使用php計算html表格中的行使用php

$rows = $table->find('#studenttable'); /*line 4 of my code*/ 
$count = count($rows);     /*studenttable is the id of my table*/ 
echo $count; 

,然後運行一個for循環插入數據的每一行。但那是一個致命的錯誤。

Notice: Undefined variable: table in savedata.php on line 4

Fatal error: Call to a member function find() on a non-object in savedata.php on line 4

反過來想可能是使用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; 

} 
?> 

仍然沒有得到結果的數量。

+2

你在問題中回答了兩次你自己的問題,你問什麼/爲什麼問我們? – SmokeyPHP

+0

是不是提交他插入的數據的表單的用戶? –

+0

我對這個問題做了一些編輯。問題在於,在提交PHP文件時返回致命錯誤,而不是打印表中的行數。 – akashaggarwaal

回答

1

您不能直接訪問PHP中的HTML元素。

我的建議是改變客戶端代碼,以便每當一行被添加到表中時,<input type="hidden" value="value-of-that-row" name="htmlrow[]"/>被添加到表單中。你可以在PHP中使用$_POST['htmlrow']訪問生成的表格行,該表格現在包含用戶數組,數據。

0
在table.php

<script> 
function addRow() 
{ 
    var table = document.getElementById("studentsTable"); 
    var row = table.insertRow(-1); 
    var cell = row.insertCell(0); 
    //get the current count of rows 
    //-1 for the head row another -1 to index from 0 
    var last_row_index = table.getElementsByTagName("tr").length-2; 

    cell.innerHTML = '<input name="name_'+ last_row_index +'" type="text" />'; 
} 

<body> 

<form action="update.php" method="post"> 
    <table id="studentsTable"> 
    <tr> 
     <th>Name</th> 
    </tr> 
    <tr> 
     <td><input name="name_0" type="text" /></td> 
    </tr> 
    </table> 
    <input name="submit" type="submit" value="Submit" /> 
    <br> 
</form> 
<button onclick="addRow()">Add New Row</button> 
</body> 

在update.php

<?php 

foreach($_POST as $name => $value) 
{ 
    if(substr($name, 0, 5) == 'name_') 
    { 
     echo $name .' : '. $value .'<br>' ; 
    } 
} 

?> 

輸出將是這樣的:

NAME_0:簡

NAME_1:鮑勃

NAME_2:山姆

多達在table.php

添加的用戶當然,你可以把它們放在一個數組,插入MySQL的....等。