2013-08-23 50 views
0

我有這樣如何添加更多的文本字段並通過在mysql中附加逗號來存儲該值?

<?php 
$mysql_db_hostname = "localhost"; 
$mysql_db_user = "root"; 
$mysql_db_password = ""; 
$mysql_db_database = "data_entry"; 

$connection = mysql_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password) or die("Could not connect database"); 
mysql_select_db($mysql_db_database, $connection) or die("Could not select database"); 

?> 

<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> 

這是一個代碼正在與不同的ID。

我的意思是,如果我插入兩個或兩個以上的業餘愛好,它應該插入在同一行中相同的ID通過附加值逗號分隔。

+1

這是什麼問題? –

+0

就像我添加兩個愛好它是在不同的行中添加一個在另一個下面,我希望它在逗號分隔的 – razor

+2

相同的行,這將是非常差的分貝設計。查看'正常化' – 2013-08-23 03:48:36

回答

0

使它有點像這樣:

foreach ($_POST['dynfields'] as $key=>$value) { 
    $values = $values.",".mysql_real_escape_string($value); 
} 
$query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES ('$values')", $connection);  
+0

兄弟如果我添加一個值說'紅'它是像紅色紅色添加兩次 – razor

+0

兄弟如果我添加一個值說'紅'它是像紅色添加兩次紅色請幫忙 – razor

1

嘗試使用破滅()函數來做到這一點,

if ($_POST['dynfields']) { 
    $values = implode(",", $_POST['dynfields']); 
    $query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES ('$values')", $connection);  
} 
+0

哇,非常感謝兄弟,它的工作! – razor

+0

Bro如果假設代碼中有默認文本框,那麼如果用戶想要添加更多。你能幫忙嗎? – razor

相關問題