简体   繁体   English

php表格提交按钮

[英]php forms submit button

I am relatively new to php. 我对php比较陌生。 I have the following problem. 我有以下问题。 Suppose I have a page with 假设我有一个页面

  • a form with two fields x, y and two buttons: submit and clear; 具有两个字段x,y和两个按钮的表单:提交和清除;
  • a table that shows the db records for x, y with two buttons, edit and delete 用两个按钮显示x,y的数据库记录的表,编辑和删除

when I enter values in the form fields and press button, submit inserts the data in the db; 当我在表单字段中输入值并按下按钮时,submit将数据插入db中; data is then shown in the table below; 数据如下表所示;

when I press edit on the table, the form is populated with the data from the selected record. 当我在表格上按Edit时,表格中将填充来自所选记录的数据。 Now I want submit to update the record and not just insert a new one. 现在,我想提交以更新记录,而不仅仅是插入新记录。

How should I proceed? 我应该如何进行?

Thanks!!! 谢谢!!!

Giuseppe 朱塞佩

you should add some hidden field in your form to differentiate the updates and insert. 您应该在表单中添加一些隐藏字段以区分更新和插入。

A good way to do that is for example to put your primary key has field 做到这一点的一种好方法是,例如,将主键置于字段中

<input name="id" type="hidden" value="<?= $row['id']"/>

after on the PHP code you can do something like this 在PHP代码上之后,您可以执行以下操作

if(isset($_POST['id']) && $_POST['id'] != 0){
 // this is an update 
 $sql = "UPDATE ...."
 ...
} else {
 $sql = "INSERt ...";
 ...
}

for the insert form just don't put the hidden input or make the value being 0 对于插入表单,只是不要放置隐藏的输入或将值设为0

First of you should be storing id of the current edit somewhere like hidden field or query string, once you have done that, you should use the update statement to update the record rather than inserting new one something like: 首先,您应该将当前编辑的ID存储在隐藏字段或查询字符串之类的位置,一旦完成,就应该使用update语句更新记录,而不要插入新的内容,例如:

// sql query
update tablename set fieldname = 'fieldvalue'......... and son

You need to show your code for getting accurate answer. 您需要显示代码以获取准确答案。

  1. Add an identifier to your rows: an ID column in the database (preferably an UNSIGNED INTEGER), which is also in the table (you can use it as a querystring in the url you use for editing an entry), and as a hidden input in the form 在行中添加一个标识符:数据库中的ID列(最好是UNSIGNED INTEGER),该标识符也位于表中(您可以将其用作用于编辑条目的url中的查询字符串),并用作隐藏输入形式
  2. If you're adding an entry, make sure the hidden input is set to null, or zero (or some other value that cannot be a valid identifier) 如果要添加条目,请确保将隐藏的输入设置为null或零(或其他不能为有效标识符的值)
  3. Whenever the form is submitted, test for the identifier to be null or something else 提交表单后,请测试标识符是否为null或其他
  4. If the identifier is null, add like you did before 如果标识符为null,则像以前一样添加
  5. If the identifier is not null, update the element with the identifier from the input 如果标识符不为空,则使用输入中的标识符更新元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM