Counting The Rows In Html Table Using Php
I have got a dynamic HTML table that allows the user to add rows on click of a button. The data from each row needs to be inserted in MySQL table for which i use the PHP script. No
Solution 1:
You cannot directly access HTML elements in PHP.
My suggestion would be altering the client-side code so that whenever a row gets added to the table, an <input type="hidden" value="value-of-that-row" name="htmlrow[]"/>
gets added to the form.
This way, when submitting the form (you have the whole thing wrapped inside a form, right?) you can access the generated table rows in the PHP handling the form using $_POST['htmlrow']
, which will now contain an array of the user data.
Solution 2:
in table.php
<script>functionaddRow()
{
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 0var last_row_index = table.getElementsByTagName("tr").length-2;
cell.innerHTML = '<input name="name_'+ last_row_index +'" type="text" />';
}
<body><formaction="update.php"method="post"><tableid="studentsTable"><tr><th>Name</th></tr><tr><td><inputname="name_0"type="text" /></td></tr></table><inputname="submit"type="submit"value="Submit" /><br></form><buttononclick="addRow()">Add New Row</button></body>
in update.php
<?phpforeach($_POSTas$name => $value)
{
if(substr($name, 0, 5) == 'name_')
{
echo$name .' : '. $value .'<br>' ;
}
}
?>
the output will be something like:
name_0 : Jane
name_1 : Bob
name_2 : Sam
.
.
As many as the user added in table.php
You can of course put them in an array, insert into MySQL....etc.
Post a Comment for "Counting The Rows In Html Table Using Php"