简体   繁体   English

如何使用PDO插入然后在同一函数中返回`lastInsertId()`?

[英]How can you insert with PDO then return the `lastInsertId()` in the same function?

How can you insert with PDO then return the lastInsertId() that was created? 如何使用PDO插入然后返回创建的lastInsertId() This can be done inside the function, but I either way I would like to get the lastInsertId() outside the function. 可以在函数内部完成此操作,但是无论哪种方式,我都希望在函数外部获取lastInsertId()

function insert_PDO($item1, $item2){

        $params =   array(
                        ":item1"        =>      $item1 ,
                        ":item2"        =>      $item2 
                    );

         $sql = "INSERT INTO table                  (column1,   column2)
                VALUES                              (:item1,    :item2)
            ";

    //return $this->insert($sql, $params);    //this one works

    //now trying this, want to return 

            $insertitems    = $this->insert($sql, $params);  
            $item_ID        = $this->lastInsertId();  
            return ($insertitems, $item_ID) ;  //does not work
}

protected function insert($sql, $params)
{
    $stmt = $this->dbh->prepare($sql);
    return $stmt->execute($params);
}

// I tried this too with the original insert:

    $results        =       $createInsert   ->  insert_PDO($item1, $item2);
    $lastid = $results[0];

    foreach($results1 as $row){
        $auditVID = $row[ID];
        $auditVID = $row[0];
    }   

Statement 声明

return ($insertitems, $item_ID) ; 

will cause syntax error. 会导致语法错误。

If you want to return several values - use array: 如果要返回多个值,请使用数组:

$insertitems    = $this->insert($sql, $params);  
$item_ID        = $this->lastInsertId();  
return array($insertitems, $item_ID) ;
// or for newer php versions:
return [$insertitems, $item_ID];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM