最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create multiple dynamic form fields and insert in mysql database - Stack Overflow

programmeradmin1浏览0评论

I need to create dynamic text fields which contains: name surname age gender. I should have a button called "add new user" which simply adds a new row where a I can type in name surname age gender. I need it dynamic because I don't know how many users will be added per event. I also need to store name surname age gender (x) amount of added rows in database.

I need something similar to below : however I need an additional 3 rows next to each other. So I will "INSERT INTO my_hobbies (name, surname, age, gender)

I know this sounds far fetched but i am struggling with this.

<?php 
require("dbconn.php");
?>

<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Hobby No. ' + counter + '</strong><br />' 
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />' );

});
});
</script> 

<body>

<?php
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
foreach ( $_POST['dynfields'] as $key=>$value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES ('$values')", $connection );  

}
}

echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";

mysql_close();
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">


<div id="container">
<p id="add_field"><a href="#"><span>Click To Add Hobbies</span></a></p>
</div>

<input type="submit" name="submit_val"  value="Submit"  />
</form>
<?php } ?>

</body>
</html>

I need to create dynamic text fields which contains: name surname age gender. I should have a button called "add new user" which simply adds a new row where a I can type in name surname age gender. I need it dynamic because I don't know how many users will be added per event. I also need to store name surname age gender (x) amount of added rows in database.

I need something similar to below : however I need an additional 3 rows next to each other. So I will "INSERT INTO my_hobbies (name, surname, age, gender)

I know this sounds far fetched but i am struggling with this.

<?php 
require("dbconn.php");
?>

<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Hobby No. ' + counter + '</strong><br />' 
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />' );

});
});
</script> 

<body>

<?php
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
foreach ( $_POST['dynfields'] as $key=>$value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES ('$values')", $connection );  

}
}

echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";

mysql_close();
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">


<div id="container">
<p id="add_field"><a href="#"><span>Click To Add Hobbies</span></a></p>
</div>

<input type="submit" name="submit_val"  value="Submit"  />
</form>
<?php } ?>

</body>
</html>
Share Improve this question asked Dec 3, 2014 at 13:12 Regardt Ogies MyburghRegardt Ogies Myburgh 1601 gold badge1 silver badge8 bronze badges 1
  • Switch to mysqli_* or PDO. mysql functions are no longer maintained. – alda1234 Commented Dec 3, 2014 at 13:26
Add a ment  | 

2 Answers 2

Reset to default 5

You already have a javascript counter so you can use it to identify which input fields belong together. According your example can use something like this:

$(function(){
    $('p#add_field').click(function(){
        counter += 1;
        $('#container').append(
        '<strong>Hobby No. ' + counter + '</strong><br />' 
        + '<input id="field_' + counter + '" name="dynfields['+counter+'][name]' + '" type="text" /><br />' +
        + '<input id="field_' + counter + '" name="dynfields['+counter+'][surname]' + '" type="text" /><br />' +
        + '<input id="field_' + counter + '" name="dynfields['+counter+'][age]' + '" type="text" /><br />' +
        + '<input id="field_' + counter + '" name="dynfields['+counter+'][gender]' + '" type="text" /><br />');

    });
});
</script>

You can catch that in your PHP in the same way. Only notice that the value is now an array instead of a single value, but you can use array_keys and array_values to create the query on an easy way. Try this in PHP:

if (isset($_POST['submit_val'])) {
    if ($_POST['dynfields']) {
        foreach ( $_POST['dynfields'] as $key=>$fieldArray ) {

            $keys = array_keys($fieldArray);
            $values = array_map("mysql_real_escape_string",$fieldArray);

            $query = mysql_query("INSERT INTO my_hobbies (".implode(',',$keys).") VALUES ('".implode('\',\'',$values)."')", $connection );  
        }
    }

    echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";

    mysql_close();
}

And yes, @alda1234 is right. You should't use mysql_* because it's deprecated.

I have the same answer with Mysqli prepared Statements enjoy it.

My html

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <p><label>Please enter your most recent education<br>
    <input type="text" name="dynfields[]">
</p>
<p><label>Please enter any previous education<br>
    <input type="text" name="dynfields[]">
</p>
<p><label>Please enter any previous education<br>
    <input type="text" name="dynfields[]">
</p>
<input type="submit" name="submit">
</form>

and the php

foreach ( $_POST['dynfields'] as $key=>$value ) {

print_r($value."<br>");

$stmt = $conn->prepare("INSERT INTO dynamic_test2 (hobbies) VALUES (?)");
$stmt->bind_param("s", $values);

$values = $conn->real_escape_string($value);


$stmt->execute();

echo "New records created successfully";


}
发布评论

评论列表(0)

  1. 暂无评论