【问题标题】:PHP multiple forms, one functionPHP多种形式,一种功能
【发布时间】:2014-10-02 14:09:26
【问题描述】:

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

我在被难住之前写的:

// 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/>";
        }
    }
} 
}

更多信息

我打算通过将提交按钮命名为“submitInsert”或“submitUpdate”来在插入/更新之间切换。经过一些数据验证后,检查插入/更新。在确定这是要走的路后,我意识到我不知道如何启动该功能。

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

有没有更好的方法来做到这一点?

【问题讨论】:

  • 那么,如果我的理解正确,您打算使用相同的函数来处理插入和更新?这是有原因的吗?

标签: php forms logic


【解决方案1】:
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)";
  }

}

【讨论】:

  • 我唯一想知道的是:如果用户尝试使用数据库中已有的订单号提交新订单,则此函数只会更新订单。它不会通知用户。相反,尝试更新输入新订单的订单的用户最终只会创建新订单。有没有办法抓住这个?
  • 订单号是唯一的,数据库应该不是用户生成的,如果用户有订单号那么他可以更新,以及你不要让用户输入他的订单号,理想情况下他会从预定义的列表中选择它。
  • 我将订单号等同于 ($id) 的错误。我的系统不会创建订单号,而另一个系统会。使用这些红色激光扫描仪之一扫描订单号。所以从逻辑上讲,用户正在创建订单号,而我的系统只是记录它。订单号仍然是唯一的,但不是数据库中自动递增的 ID。
  • 您是否无权访问生成订单号的数据库,如果有,那么您可以简单地交叉引用?最简单的方法是在生成订单号时将其插入到表中,之后的所有内容都是更新。
  • 我无权访问其他数据库。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多