【问题标题】:Using Adodb for php/postgresql, return row ID after insert使用 Adodb for php/postgresql,插入后返回行 ID
【发布时间】:2010-02-22 04:36:08
【问题描述】:

当我插入一行时,它使用 SERIAL 递增 ID 字段。

如何在插入后立即返回新创建的 ID 号?

(数据库是 Postgresql。)

【问题讨论】:

    标签: php postgresql adodb-php


    【解决方案1】:
    $db->Insert_ID();
    

    【讨论】:

      【解决方案2】:

      这段代码运行良好:

      $insertId = $adodb->getOne("INSERT INTO test (str) values ('test') RETURNING id");
      

      【讨论】:

        【解决方案3】:

        将您的 INSERT 视为 SELECT 并在您的 INSERT 查询中使用 RETURNING:

        INSERT INTO foo (bar) VALUES('Doe') RETURNING id;

        获取结果,您就完成了。从 8.2 版开始工作

        【讨论】:

          【解决方案4】:

          adodb 中的Insert_ID() 返回空值,或者在某些情况下返回 0。

          我工作的postgresql是9.1版本。

          $_sql = 'INSERT INTO '.$_table.' (';
          $_sql .= implode(', ',$arr_fld_names);
          $_sql .= ") VALUES ('";
          $_sql .= implode("', '",$arr_fld_values);
          $_sql .= "')";
          
          if ($echo){
              echo $_sql;
          }
          
          $_return = $this->Execute($_sql);
          $this->mLastInsertedId = $this->mConn->Insert_ID(); // Keep track of the last inserted ID.
          

          编辑: 我添加了一个肮脏的方式:

          $_sql = 'INSERT INTO '.$_table.' (';
          $_sql .= implode(', ',$arr_fld_names);
          $_sql .= ") VALUES ('";
          $_sql .= implode("', '",$arr_fld_values);
          $_sql .= "') RETURNING id";
          
          if ($echo){
              echo $_sql;
          }
          
          $_return = $this->Execute($_sql);
          preg_match_all('/([\d]+)/', $_return, $ret_val);
          $this->mLastInsertedId = $ret_val[0][0]; // Keep track of the last inserted ID.
          

          【讨论】:

            【解决方案5】:

            我喜欢使用adodb 来避免编写SQL。我需要在 table1 上插入一条带有 text1 的记录,同时在 table2 上插入一条记录以及其他数据和在 table1 上创建的 ID 作为参考。我喜欢使用事务的想法和AutoExecute

            $db->StartTrans();
            {
                $array_table1 = array('text_field'=>'text1');
                $db->AutoExecute("table1", $array_table1, 'INSERT');
            
                if ($lastid=$db->Insert_ID()) {
                    $array_table2=array(
                        'text_field'=>'other text',
                        'id_of_table1'=>$lastid);
                    $db->AutoExecute('other_table', $array_table2, 'INSERT');
                } else {
                    $db->RollbackTrans();
                }
            
            }
            $db->CompleteTrans();
            $result=$db->_transOK;
            

            Autoexecute 仍然缺少返回Insert_Id() 的选项

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-10-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-07-05
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多