我有一个简单的HTML表单,其中包含多个字段(如id,name,contact和email)。一旦用户填写表单并提交表单,数据将存储在数据库中,同时(即使在同一页面上),表格将显示已存储的数据。
现在,我想在表格底部放置一个更新按钮。当用户点击它时,他们可以查看将预填充他们先前输入的数据的表单,因此他们不需要输入两次数据。
我该怎么做?如何根据id字段捕获其他字段?
答案 0 :(得分:3)
您必须使用如下所述的javascript和ajax代码。尝试理解它。
<script type="text/javascript">
$(document).ready(function(e) {
$.ajax({
//Your ajax here...
success: function(response) {
//Your code of showing inserted data in table....
//get the inserted userid from response and set update button's ONCLICK attribute as mentioned below
var userid = getuseridfromresponse;
$("#updatebuttonid").attr("onclick","updaterecord("+userid+")");
}
});
});
function updaterecord(userid){
$.ajax({
//your ajax here you
//send all the details from php code using JSON or whatever you are using.
success: function(response) {
//store all the data into js variables.
var userid = response.userid;
var fullname = response.fullname;
// and so on..
$("#fullname").val(fullname); //this will set the textbox value to fullname
//and so on..
$("#userid").val(userid); //this is a hidden input in inser form. by default it will be zero. you will need it while updating.
$("#actionname").val("update"); //this is also hidden input in insert form. default value would be "insert"
// you just need to check in php that which actionname you are getting.
//if you will get actionname = insert Do insert code
//if you will get actionname = update Do update code.
}
});
}
</script>
答案 1 :(得分:1)
点击表格数据后,将其ID传递给它。然后查看ID&amp;从数据库中获取数据并以html格式设置值。如果传递了ID,则更新应该是没有ID,它应该是新的插入。
答案 2 :(得分:1)
这些是简单的数据库操作。网上有很多教程,google它。 您可以参考this。
答案 3 :(得分:1)
如果您想要在不刷新页面的情况下在页面上显示新条目,请使用AJAX
..
否则刷新页面并使用Select query
显示新条目。
对于第二个问题..在更新按钮上按Select query
,然后在echo
的{{1}} value
中使用HTML input fields
这是一个简单的方法..
// php code
$result = mysql_query('Select * from table_name WHERE id = 1');
$row = mysql_fetch_assoc($result);
// use loop if query return multiple rows
// HTML code
<input type = "textbox" name="age" value="<?php echo $row['age'] ?>">
答案 4 :(得分:1)
带有更新按钮的表单需要{id}的hidden
字段。然后,PHP需要从数据库中选择与id相对应的记录,并以表格形式显示它。
如果每个页面只有一条记录,您可以将预填表格放在div
与表格相同的页面上。然后,您可以使用JavaScript来隐藏
页面加载时显示div
,并在用户点击更新按钮时显示div
。