在同一页面上添加/编辑时出现PHP问题

时间:2011-03-13 07:00:53

标签: php

目前我在php / mysql驱动的网站中添加和编辑记录时使用的是同一页面。添加工作正常,但更新时有一个问题,我正在寻求帮助。

共有2页 managedata.php显示表中的记录,并编辑记录有一个编辑按钮,我发送2个值update = 1和id = n(我将编辑的数据的ID),它带我像这样的adddata页面

adddata.php?update=1&id=7

并且在adddata页面中,如果我编辑字段并在第一次拍摄中单击“保存”,则它可以正常工作 但如果有任何错误并且我显示错误,那么网址将更改为

adddata.php 因此更新模式将为false并创建新记录

我正在寻求这个问题的帮助。 1)如何在querystring中设置值(页面重新加载的时间),因此updatemode将始终为1.

谢谢

2 个答案:

答案 0 :(得分:2)

如果要根据用户的输入选择是否将插入新记录更新到数据库中,请通过URL告知脚本要执行的操作,然后根据该信息处理信息。

示例:假设您通过URL将信息传递给脚本add_data.php?update = new_entry& id = 0或add_data.php?update = new_entry

或add_data.php?update = old_entry& id = 7

然后做这样的事情:

if (empty($_POST['id'])) {
        $id = FALSE;
    } else {
        $id =  (int) $_POST['id']; //Be sure that the id value received is a number with (int)
}   

//So what are we doing again? Editing or adding new record?
if (empty($_POST['update'])) {
        $update= FALSE;
    } else {
        $update=  $_POST['update']; 
}   


$stamp = md5(uniqid(rand(), true)); // I like to do this because every entry into the database would then be unique, and we can always edit without the system saying we are making duplicate content. This is good in case the user tries to edit and doesn't really edit but presses enter. 
if ($update && $update == 'new_entry') { //Check that everything went well with validations above. We don't check here for an id because this is a new record and so there should be no id after all. 
    //Insert new record into the database

} elseif ($id && $id != 0 && $update && $update == 'old_entry') {
    //Update the database
}

答案 1 :(得分:0)

只需通过 id 进行检查即可 添加新记录时,您不需要ID。检查它

$id = $_REQUEST['id'];
if(!empty($id)){
//add mode;
}
else
{
    //edit mode
}

在编辑模式下 简单地添加隐藏字段,如

<input type="hidden" name="pid" value="<?php echo $_REQUEST['id']; ?>" />

在添加模式下,pid将为空并且编辑模式它将具有一些值,因此您可以再次检查上面的代码

Here if empty

//insert query

else

// update query