将数据添加到与id连接的两个表中

时间:2014-06-15 20:38:57

标签: php mysql sql pdo

大家好,我有这个代码将数据插入mysql数据库到表radnici

 try {        
                $STH = $db->prepare("INSERT INTO radnici (ime_prezime, jmbg, grad, ulica, posta, telefon, uloga, email, user_id) VALUES (:1,:2,:3,:4,:5,:6,:7,:8,:9)");

                $STH->bindParam(':1', $_POST['ime']);
                $STH->bindParam(':2', $_POST['jmbg']);
                $STH->bindParam(':3', $_POST['grad']);
                $STH->bindParam(':4', $_POST['ulica']);
                $STH->bindParam(':5', $_POST['posta']);
                $STH->bindParam(':6', $_POST['telefon']);
                $STH->bindParam(':7', $_POST['pozicija']);
                $STH->bindParam(':8', $_POST['email']);
                $STH->bindParam(':9', $user_id);

//HERE I NEED TO INSERT DATA TO TABLE WORKHOURS BUT CONNECTED WITH JUST ADDEDED ID
//SO here I NEED query something like this // INSERT INTO radnici (ID, ID_radnici, ime_prezime, jmbg,... here ID_radnici is =with ID from table radnici of added data


                $STH->execute();

            } catch (PDOException $e) {
                echo $e->getMessage();
            }
            echo "<p>Data submitted successfully</p>";

所以现在当我添加这个时,我需要在这个表中添加workhours数据,但是只用添加的数据与ID连接......

所以在第二个表中我有:ID, ID_radnici (here I must add ID_radnici same value as ID on table radnici), value, user_id

我写这个但是没有工作: UPDATE:

 try {        
                $STH = $db->prepare("INSERT INTO radnici (ime_prezime, jmbg, grad, ulica, posta, telefon, uloga, email, user_id) VALUES (:1,:2,:3,:4,:5,:6,:7,:8,:9)");

                $STH->bindParam(':1', $_POST['ime']);
                $STH->bindParam(':2', $_POST['jmbg']);
                $STH->bindParam(':3', $_POST['grad']);
                $STH->bindParam(':4', $_POST['ulica']);
                $STH->bindParam(':5', $_POST['posta']);
                $STH->bindParam(':6', $_POST['telefon']);
                $STH->bindParam(':7', $_POST['pozicija']);
                $STH->bindParam(':8', $_POST['email']);
                $STH->bindParam(':9', $user_id);

                $orderID = $db -> lastInsertId();

   $STH1 = $db->prepare("INSERT INTO workhours (ID_radnika) values($orderID)");  // where $value is the value you want to insert...
   $STH->execute();
      $STH1->execute();






            } catch (PDOException $e) {
                echo $e->getMessage();
        }
        echo "<p>Data submitted successfully</p>";

2 个答案:

答案 0 :(得分:1)

使用lastInsertId将执行您想要的操作:

$orderID = $db -> lastInsertId();

答案 1 :(得分:0)

使用lastInsertId()并使用从其返回的值将数据插入到另一个表中。

这样的事情:

int $lastID = $db->lastInsertId();
if ( $lastID ) {
   $STH = $db->prepare("INSERT INTO workhours (ID_radnici, value, userid) values($lastID, $value, $user_id)");  // where $value is the value you want to insert...
   $STH->execute();
}