2012-11-19 117 views
0

我正在制作一个非常简单的PHP应用程序,它将表单中的信息存储在数据库中,然后允许编辑该信息。重复使用或重新创建数据库插入脚本

我的表格和存储信息在数据库中工作很好。我用它来存储信息从我的形式数据库的代码(之后被缩短这个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)来插入数据库以更新数据库中的信息,或许检查它是如何调用的,还是应该创建一个新的单独页面用于更新操作。

什么是更好的方法?

回答

1

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

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

}elseif(!empty($_POST['id'])){ 
     //update operation 
} 
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 
} 

希望帮助