2015-06-04 39 views
0

我有一個關於數據庫的問題,我正在使用活動的recordsCodeigniter。數據庫結構的可能性

邏輯是這樣的:我有一個表,假設它的名字是A,表A有4個字段,例如:uniqueID,typeofID,date和userID。

第一步:我(用戶)使用條件uniqueID和typeofID對錶A進行驗證。如果該行爲true或uniqueID可用,則返回成功。

第二步:如果驗證成功,則用戶可以將數據插入到一個新表中,讓我們說表是B.在表B中有ID和額外A.I(自動增量)。在表B中有4個字段:id,username,question1,question2。

問題是:我可以插入表B ID到字段用戶ID表A嗎? 這樣,當有人訪問表A時,通過知道用戶ID,他將知道表A中的用戶名是什麼。

============================================== ===========================

從成員的解決方案,已經成功。 首先我使用表uniqueID插入數據到表B並獲取最後一個id,然後插入數據。

這是我的解決方案

$this->db->insert('tableB', $data); 
$result = $this->db->insert_id(); 

$this->db->where('uniqueID', $data2['uniqueID']); 
$result2 = $this->db->update('tableA', array('idfromtableB' => $result)); 

return $this->db->affected_rows(); 

但我有錯誤與ODBC INSERT_ID()。錯誤說: 一個PHP錯誤遇到

嚴重性:注意

消息:未定義的屬性:CI_DB_odbc_driver :: $ DB

文件名:ODBC/odbc_driver.php

行號:239

回溯:

<p style="margin-left:10px"> 
     File: C:\xampp\htdocs\myproject\application\models\users_m.php 
    <br /> 
     Line: 79 
    <br /> 
     Function: insert_id   
</p> 

========================================== ===============================

找到了解決辦法在這裏:SQL Server last insert id return array in CodeIgniter

回答

1

插入到表B中後,使用$user_id = $this->db->insert_id()得到最後插入ID(表B的ID),然後更新表A.所以,你的代碼看起來像

... 
$this->db->insert('tableA',$data); 
$last_rowID = $this->db->insert_id(); 
$this->db->insert('tableB',$dataB); 
$user_id = $this->db->insert_id(); 
$this->db->where('tableA_ID',$last_rowID)->update('tableA',array('userID' => $user_id)); 
+0

我很抱歉,我沒有將數據插入到tableA中,我只是檢查數據是真是假。如果錯誤,驗證將不會成功。如果成功,我可以繼續向tableB插入數據並更新tableA。如果我只是使用3行下來(我的意思是插入tableB和insert_id())@ rejoanul-alam –

+0

所以你可以得到表A的行ID(成功返回)&現在你的$ last_rowID將是'$ last_rowID = $ success [0] ['row_ID']'然後更新表A.所有你需要做的就是獲得表A的行ID。現在有想法? –

+0

是的,我知道你的意思。但是,表A已經填寫了數據。我不會插入任何數據。那麼如果表A的數據有27個ID,而表B是0呢?在想到一個詭計之後,我想這是不可能的。 @ rejoanul-alam –

0

是你可以,你只需要加入你的表:

例如:

public function get_info($id){ 
    $this->db->select('*'); 
    $this->db->from('tableA'); 
    $this->db->join('tableB' ,tableA.id=tableB.id); 
    $this->db->where('tableA.id' , $id); 
    $query = $this->db->get(); 

    return $query->result_array(); 

} 

好心修改它,以便將適合在你的代碼。

+0

我可以先插入第一個數據爲表B和然後將表ID插入列userID表A? @xammeil –

+0

是的,你可以,,,所以這意味着你將在表A中有一個外鍵。你需要在表A中放置另一列來指定表B上的ID並將它用作表中的連接。 – aizele