大家好我在下面有这个代码,它会动态添加每个点击的文本框。我的问题是如何将动态创建的文本框保存到MYSQL数据库
我想保存每行中的每个文本框。意思是一个文本框=一行
e.g
ID | NAME | Training (the textbox)|
1 john Driving
2 john swimming
3 john running
<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
<!--
#main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<form role="form" method="post">
<label for="box1"><span class="namer">Name</span></label>
<input type="text" name="name" />
<p class="text-box">
<label for="box1">Box <span class="box-number">1</span></label>
<input type="text" name="boxes[]" value="" id="box1" />
<a class="add-box" href="#">Add More</a>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('.my-form .add-box').click(function(){
var n = $('.text-box').length + 1;
if( 5 < n ) {
alert('Stop it!');
return false;
}
var box_html = $('<p class="text-box"><label for="box' + n + '">Box <span class="box-number">' + n + '</span></label> <input type="text" name="boxes[]" value="" id="box' + n + '" /> <a href="#" class="remove-box">Remove</a></p>');
box_html.hide();
$('.my-form p.text-box:last').after(box_html);
box_html.fadeIn('slow');
return false;
});
$('.my-form').on('click', '.remove-box', function(){
$(this).parent().css( 'background-color', '#FF6C6C' );
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.box-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
</body>
</html>
// MY PHP Insert code
<?php
$con = mysql_connect("localhost","root","");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("SLL",$con);
//please assume boxes = training
$name = $_POST['name'];
$training= $_POST['boxes'];
$AddQuery ="INSERT INTO db (name,training)VALUES ($name,training)"
mysql_query($AddQuery, $con);
?>
答案 0 :(得分:2)
几乎在那里(除了奇怪的拼写错误),$_POST['boxes']
是一个数组,所以只需通过数组中的每个键来循环(explanation)。
<?php
$con = mysql_connect("localhost","root","");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("SLL",$con);
$name = $_POST['name'];
//please assume boxes = training
foreach($_POST['boxes'] as $textbox){
$training= $textbox;
$AddQuery ="INSERT INTO db (name,training)VALUES ($name,$training)";
mysql_query($AddQuery, $con);
}
?>
<强>更新强>
要使用两个或更多输入数组(即name="boxes[]"
和name="amount[]"
)进行循环,需要假设每个boxes[]
都相对于amount[]
,即{{1}与boxes[0]
相同,amount[0]
与boxes[1]
相符,amount[1]
与boxes[n]
相符。因此,每次循环结束/重新启动时,您都需要一个递增计数器。请参阅amount[n]
,您会看到$i
的值在每次循环结束时增加1,并且按键的数量为$i
。
修改后的循环类似于
$_POST['amount'][$i]