Here's the PHP for processing the form:
<?php
// before form submitted $_POST has a null value
if( isset($_POST) && $_POST != null) {
$post = $_POST['filter_attr'];
// assuming an input contains only alphabetical characters
if ( ctype_alpha( $post ) || is_array( $post ) ) {
// var_dump($post);
// rest of processing, i.e. create insert query ...
}
else
{
// the data is unacceptable, so you may wish to end the script.
exit;
}
}
?>
Here's the JavaScript:
<script language="javascript">
var i = 1;
function changeIt()
{
var d = document;
d.getElementById("my_div").innerHTML += "<br>";
d.getElementById("my_div").innerHTML += "<input type='text' size='70' id='filter_attr" + i + "' name='filter_attr[]'><br>";
i++;
}
</script>
PHP will recognize that the submitted form contains an array of filter_attr data if the name attribute of the static and dynamic inputs is "filter_attr[]". However, the id must be unique if you wish JavaScript to access it using document.getElementById
. Thus the first dynamic input has an id of "filter_attr1" and a name of "filter_attr[]".
Please note:
it is better to write:
document.getElementById("my_div")
than to use the id or name directly (see discussion at Why don't we just use element IDs as identifiers in JavaScript?)
Creating dynamic inputs is preferable using the DOM and its methods, If you wish, you may use jQuery which simplifies working with DOM.
The above HTML seems to be missing a submit button. However, even if it is present in the actual code, the following code does not work:
if ( isset( $_POST['submit'] ) && $_POST['submit'] == "Submit") {
When a form gets submitted via a POST or a GET request, what gets submitted are key-value pairs of data, i.e. data coming from form elements where the user had to supply some kind of response whether it's text or marking a checkbox or radio button. The submit button facilitates submitting the data but it itself does not get submitted if you fail to name and the name must be the same as its type, i.e. "submit". I respectfully suggest the way my preceding PHP code does which answers the questions, "Was a form submitted? And, if so does it contain any data?"
The code needs to assume that the post could be tainted. That means you need to validate the posted data before using it.
The mysql extension has been deprecated as of PHP5.5; see discussion at The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead.
Lastly, using an HTML TABLE should be restricted for displaying tabular data and should not be used for layout. Instead, use DIV elements and by styling them you can achieve the desired layout. This result will be semantically correct and save on memory.