gpt4 book ai didi

javascript - php使用foreach post向mysql添加多条数据

转载 作者:行者123 更新时间:2023-11-29 00:06:35 25 4
gpt4 key购买 nike

你好,我有以下 javascript,它填充了我的字段并且工作正常

<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field2').click(function(){
count += 1;
$('#container').append(
'<strong>Link #' + count + '</strong><br />'
+ '<input id="field_' + count + '" name="fields[]' + '" type="text" /><input id="field1_' + count + '" name="idrima' + '" type="text" /><input id="field2_' + count + '" name="code_title' + '" type="text" /><input id="field3_' + count + '" name="name_title' + '" type="text" /><input id="field4_' + count + '" name="vathmos_title_a' + '" type="text" /><input id="field5_' + count + '" name="vathmos_title_d' + '" type="text" /><input id="field6_' + count + '" name="etos' + '" type="text" /><br />');

});
});
</script>

我的问题是,当我使用 foreach 时,我只能添加最后一个字段填充,而不是全部。所以我认为 foreach 不起作用,因为只添加了最后一条记录。我的代码是

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 spoudes (idrima,code_title) VALUES ('%s','%s')",
mysql_real_escape_string($_POST['idrima']),
mysql_real_escape_string($_POST['code_title']));
$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 spoudes_link (id_fakelos, id_spoudes) 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);


}

最佳答案

你应该使用 <input name="idrima[]"><input name="code_title">因为每次添加新字段时,都会覆盖帖子中的该字段。

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

//Insert into websites table
$sql_website = sprintf("INSERT INTO spoudes (idrima,code_title) VALUES ('%s','%s')",
mysql_real_escape_string($_POST['idrima'][$key]),
mysql_real_escape_string($_POST['code_title'][$key]));
$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 spoudes_link (id_fakelos, id_spoudes) 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);


}

关于javascript - php使用foreach post向mysql添加多条数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27216676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com