将动态创建的元素的值存储到数据库PHP MySql [英] store dynamically created elements' value to database PHP MySql
问题描述
newbie.我有一个表单,用户可以单击一个按钮来添加输入文本元素.我使用JQuery做到了这一点.
newbie here.. I have a form where a user can click a button to add an input text element. I did this using JQuery.
我要完成的是将动态添加的文本框的值保存到数据库中.
What I want to accomplish is to save the values of the dynamically added textboxes to the database.
我在下面有以下代码,但是存储到数据库的工作不正常.
I have the following code below but storing to database is not working as it should be.
HTML代码:
<form id='myform' action='save.php' method='POST'>
<input type='button' value='Add Another User' id='auser'>
<input type='text' id='user' name='user'>
<input type='submit' value='Save User/s' name='submit'>
</form>
JQUERY代码:
$('#auser').on('click', function() {
$('#myform').append("<input type='text' id='user' name='user'>");
});
PHP代码(success.php):
<?php
if (isset($_POST['submit'])){
$username = $_POST['user'];
$qry=$con->prepare('INSERT INTO userslist (username) VALUES (?)')
$qry->execute(array($username));
}
?>
在此先感谢您的帮助.
推荐答案
除了上面注释中提到的错别字外,您还需要在用户字段的HTML表单输入中创建分组名称.因此,您需要将其更改为:
Aside from the typos mentioned in the comments above, you'll need to create a grouping name in your HTML form inputs on the user field. So you'll need to change it into:
<input type='text' class='user' name='user[]'>
// ^
旁注:我建议只使用class
.
之后,您还需要更改生成多个文本框字段的JS:
After that, so you'll also change the JS that spawns multiple textbox fields:
$('#auser').on('click', function() {
$("<input typ='text' id='class' name='user[]'><br/>").insertBefore('.user').last();
// ^ need to add those too
});
之后,当您提交页面(PHP)时,将得到一个数组而不是一个值:
After that, when you submit the page (the PHP), you'd get an array instead of one value:
$usernames = $_POST['user']; // this is now an array of usernames
然后在您的查询中,由于它是动态的,因此您还需要使用那些PDO占位符动态创建查询.最后,您将需要这些:
Then in your query, now that its dynamic, you'll need to create the query dynamically too using those PDO placeholders. In the end you'll need these:
if(isset($_POST['submit'])) {
$usernames = $_POST['user'];
$query = 'INSERT INTO userslist (username) VALUES '; // base query
// dynamically build placeholders
$placeholders = implode(',', array_fill(0, count($usernames), '(?)'));
$final_query = $query . $placeholders;
// the final query would look like
// INSERT INTO userslist (username) VALUES (?),(?),(?)
$qry = $con->prepare($final_query); // prepare
$qry->execute($usernames); // bind the user names
}
这篇关于将动态创建的元素的值存储到数据库PHP MySql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!