如何在php中将动态创建的文本框值插入db

时间:2014-09-02 06:20:08

标签: php jquery mysql sql database

我的名字是fairooj,我是php和jquery的新手。我有个问题。我想要你的帮助。

<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<strong>Link #' + count + '</strong><br />' 
+ '<input id="field_' + count + '" name="fields[]' + '" type="text" />'
+ '<input id="code_' + count + '" name="code[]' + '" type="text" /><br />' );

});
});
</script> 

这是我添加更多文本框的脚本..

这是我将其插入数据库的代码

<?php
//If form was submitted
if (isset($_POST['btnSubmit'])) {

//create instance of database class
$db = new mysqldb();
$db->select_db();

//Insert static values into users table
$sql_user = sprintf("INSERT INTO users (Username, Password) VALUES ('%s','%s')",
mysql_real_escape_string($_POST['name']),
mysql_real_escape_string($_POST['password']) );  
$result_user = $db->query($sql_user);


//Check if user has actually added additional fields to prevent a php error
if ($_POST['fields']) {

//get last inserted userid
$inserted_user_id = $db->last_insert_id();

//Loop through added fields
foreach ( $_POST['fields'] as $key=>$value ) {

//Insert into websites table
$sql_website = sprintf("INSERT INTO websites (Website_URL, web_Link) VALUES ('%s', '%s')",
      mysql_real_escape_string($value), mysql_real_escape_string($value) );  
$result_website = $db->query($sql_website);
$inserted_website_id = $db->last_insert_id();


//Insert into users_websites_link table
$sql_users_website = sprintf("INSERT INTO users_websites_link (UserID, WebsiteID) VALUES ('%s','%s')",
      mysql_real_escape_string($inserted_user_id),
  mysql_real_escape_string($inserted_website_id) );  
$result_users_website = $db->query($sql_users_website);

}

} else {

?>

**问题web_Link sql表正在重复Website_URL表值....

请问我怎么解决这个问题

我在等你的回复.. **

2 个答案:

答案 0 :(得分:0)

假设你在看这个?

$code=$_POST['code'];
$fields=$_POST['fields'];

mysql_real_escape_string($value), mysql_real_escape_string($code[$key]) );  

详细

$countKey=0; // add this Line

//foreach ($_POST['fields']) {
for($i=0;$i<count($fields);$i++){

   $result_website = $db->query("INSERT INTO websites (Website_URL, web_Link) VALUES ('".$fields[$countKey]."', '".$code[$countKey]."')");  

  $countKey=$countKey+1; // add this Line
}

答案 1 :(得分:0)

如果我有两个数组插入数据库,那么我有一种计算数组大小的方法示例如下

$arry1=array("abc","def");
$arry2=array("efg","hij");
$count=sizeof($arry1);
for($i=0;$i<$count;$i++)
{
     echo $sql="INSERT INTO tablename (`col1`,`col2`) VALUES (".$arr1[$i].",".$arry2[$i].")";
}