0

我正在使用 PHP 制作一个非常简单的 webapp,它将表单中的信息存储在数据库中,然后允许编辑该信息。

我在数据库中的表单和存储信息工作得很好。我用来从我的表单中将信息存储在数据库中的代码(在为此 Q 缩短之后)如下:

<?php
require_once 'connect.php';
$firstName = $_POST['firstName'];     //other variables ommited for brevity

$sth = $dbh->prepare("INSERT INTO users(firstName, lastName, country, roomtype, roomnumber, checkin, nights)
VALUES ('$firstName', '$lastName', '$country', '$roomtype', '$roomnumber', '$checkin', '$nights')");
$sth->execute();

$dbh =null;
?>

我有一个编辑页面,在那里我将数据库中的值读入表单字段。

但是,如果进行了更改,我不想向数据库添加新记录,而是更新现有记录。

我应该使用插入数据库的同一个 PHP 页面(称为 process.php)来更新数据库中的信息,也许检查它是如何被调用的,还是应该为更新操作创建一个新的单独页面.

更好的方法是什么?

4

2 回答 2

1

对于更新,您将拥有一个唯一的id,使用该 ID,您可以像这样在同一页面中执行相应的操作

if(empty($_POST['id'])) {
       //insert operation

}elseif(!empty($_POST['id'])){
       //update operation
}
于 2012-11-19T04:06:18.237 回答
0

我建议使用相同的页面来添加/编辑/删除数据库中的数据,并使用如下切换案例:

//get the action to be performed like add or edit
$action = strtolower( trim( $_POST['action'] ) );
switch($action) {
    case "add":
         //call function to insert to db
         yourFunctionToInsert();
    break;
    case "edit":
        //call function to edit
        yourFunctionToEdit();
    break;
    default:
       //some default code in case no valid action is encountered
}

function yourFunctionToInsert() {
   //code to insert to DB
}

function yourFunctionToEdit() {
   //code to update the DB
}

希望有帮助

于 2012-11-19T04:02:39.933 回答