PHP多种形式,一种功能

时间:2014-10-02 14:09:26

标签: php forms logic

逻辑让我感到困惑。我想编写一个函数来处理多个表单。我在不同的网页上有八个订单。他们都使用相同的数据库。该函数需要处理插入函数或更新函数。

在我被困之前写的是什么:

// I might want to move this IF further down in the logic
// I wasn't sure what to put here in it's place.
if(isset($_POST['submitInsert']))
{

// setting up a loop to go through all the POST values
foreach($_POST as $name => $value) 
{ 
    // make sure POST values are set before wasting
    // any time doing stuff with them
    if($value!="")
    {

        // checking if the POST value is an array because
        // an array would have to be handled differently
        if(!is_array($value))
        {
            // Just printing info for now, Thinking maybe I should 
            // do an IF here to check for insert/update
            echo $name . " --- " . $value . "<br>";

        }
        else
        {
            // for an array, I'll need another foreach statement
            echo "$name"." --- ";
            print_r($value);
            echo "<br/>";
        }
    }
} 
}

更多信息

我计划通过命名提交按钮&#39; submitInsert&#39;来切换插入/更新。或者&#39; submitUpdate&#39;。经过一些数据验证,检查插入/更新。在决定这是要走的路之后,我意识到我不知道如何启动这个功能。

表单元素名称与db字段名称匹配,因此SQL查询不应该是困难的。

有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

if(isset($_POST['submit']))  
{
  //could use for loop but you know the fields you will be using for your sql.
  $id = $_POST['id'];
  $var1 = $_POST['var1']; 
  // Do a select see if it exists if it does use update else use insert.
  $query = "SELECT * from table where ID = $id";
  if($rowCount > 0)
  {
   $query = "Update table set var=$var1 where id = $id";
  }
  else
  {
   $query = "Insert into table (var1) VALUES ($var1)";
  }

}