如何在另一个表中插入最后插入的id

时间:2016-03-30 08:01:06

标签: php mysql pdo

表1

 $tblename="Table_staff";
    $ob->insert_data($tblename,array("username" => $staffmail, "name" => $staffname,"address" => $staffadrs, "email" => $staffmail));

表2

$tblename="users";
$ob->insert_data($tblename,array("user_name" => $staffmail, "password" => $staffphone,"name" => $staffname, "staff_id" => "First table ID"));

这是我的插入功能

public function insert_data($table, $array)
     {
         $fields=array_keys($array);
         $values=array_values($array);
         $fieldlist=implode(',', $fields); 
         $qs=str_repeat("?,",count($fields)-1);
         $ssQuery = $this->conn->prepare("insert into $table(" .$fieldlist . ") values (${qs}?)");
         $ssQuery->execute($values);
         $insid=$this->conn->lastInsertId();

     }

我在第一个表中插入一些值...在第二个表'staff_id'这里插入第一个表id如何解决这个问题请帮帮我..

1 个答案:

答案 0 :(得分:-1)

使用参数$getLastId返回上次插入的ID并将其传递给下一个要插入的数组。

public function insert_data($table, $array,$getLastId = false)
         {
             $fields=array_keys($array);
             $values=array_values($array);
             $fieldlist=implode(',', $fields); 
             $qs=str_repeat("?,",count($fields)-1);
             $ssQuery = $this->conn->prepare("insert into $table(" .$fieldlist . ") values (${qs}?)");
             $ssQuery->execute($values);
             if($getLastId == true){
                return $insid=$this->conn->lastInsertId();
             }else{
                return true;
             }
         }

表1

 $tblename="Table_staff";
    $staff_id =     $ob->insert_data($tblename,array("username" => $staffmail, "name" => $staffname,"address" => $staffadrs, "email" => $staffmail),true);

表2

$tblename="users";
$ob->insert_data($tblename,array("user_name" => $staffmail, "password" => $staffphone,"name" => $staffname, "staff_id" => $staff_id));