2013-12-19 71 views
0

我有一個是這樣的搜索文件並將其存儲在一個變量PHP

1 wordsgohere 
2 morewordsgohere 
3 yougetthepoint 

我要分配的一個字符串上面那個人的USER_ID的文本文件。所以說你是第三個註冊的人,你的user_id是3,你的deposit_id是'yougetthepoint'。但是,當我回顯user_id時,即使數據庫中有2或3個用戶,並且在查看數據庫時,它的值始終爲0,因此ID號會增加。它也不會將用戶置於數據庫中。如果我用其他東西替換deposit_id,它會將用戶放入數據庫中。我認爲這是因爲new_str從來沒有被定義。

// id of new user 
    $user_id = $this->db_connection->lastInsertId(); 

    echo $user_id; 

    // searches text file for address 
    $lines_array = file("test.txt"); 

    foreach($lines_array as $line) { 
    echo $line; 
      if(strpos($line, $user_id) != false) { 
        list(, $new_str) = explode($user_id, $line); 

      } 
    } 


    // write new users data into database 
    $query_new_user_insert = $this->db_connection->prepare('INSERT INTO users (deposit_id, user_name, user_password_hash, user_email, user_activation_hash, user_registration_ip, user_registration_datetime) VALUES(:deposit_id, :user_name, :user_password_hash, :user_email, :user_activation_hash, :user_registration_ip, now())'); 
    $query_new_user_insert->bindValue(':deposit_id', $new_str, PDO::PARAM_STR); 
    $query_new_user_insert->bindValue(':user_name', $user_name, PDO::PARAM_STR); 
    $query_new_user_insert->bindValue(':user_password_hash', $user_password_hash, PDO::PARAM_STR); 
    $query_new_user_insert->bindValue(':user_email', $user_email, PDO::PARAM_STR); 
    $query_new_user_insert->bindValue(':user_activation_hash', $user_activation_hash, PDO::PARAM_STR); 
    $query_new_user_insert->bindValue(':user_registration_ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR); 

    $query_new_user_insert->execute(); 

任何幫助將是偉大的,謝謝。

+2

在執行INSERT之前調用'lastInsertId()'。你期望它能預測未來嗎? – Barmar

+0

'list(,$ new_str)= $ line'不能工作。當你使用list()時,該值必須是一個數組,而不是一個字符串。你的意思是叫'explode()'? – Barmar

+1

你的'strpos()'檢查不好。如果'$ user_id'是'3'而'$ line'是'13 something',它將匹配。您應該爆炸這一行,並將用戶ID與數組的第一個元素進行比較。 – Barmar

回答

0

正如有些人在您的評論中提到的,您應該檢查報表的順序。

首先將行插入到數據庫中。在執行時,數據庫將生成您可以隨後檢索的ID。

現在您想將Deposit_id添加到生成的條目中。只需更新條目(UPDATE users SET deposit_id=:deposit_id WHERE user_id=:user_id;)。

但我想你會得到一個你不想要的結果。

textfile中的數字是否真的是user_id?或只是一個枚舉?你可以解析它並按照文件的順序創建一個包含deposit_id的數組。現在您可以通過爲每個陣列輸入一個插入來插入所有行

+0

訂單已修復。我試過你發佈的代碼,但沒有奏效。文本文件中的數字只是枚舉。我想,擺脫這一點,按照你所說的做法會以不止一種方式提高效率。現在我只是將這個值插入數據庫的問題。 – SolidCloudinc

+0

好吧,以便您可以在沒有deposit_id的情況下將條目添加到數據庫中。該專欄有哪些屬性?它是一個外鍵嗎?或者它只是一個沒有任何鏈接到另一個表的隨機字符串?也許你應該考慮將這些信息放入另一個表中,因爲除了deposit_id外,您將有2個條目包含幾乎相同的信息。 –

相關問題