2016-03-30 17 views
0

HTMLフォームから取得した値をloginDetailsとmemberDetailsの2つのテーブルに挿入するにはどうすればいいですか? (コードに示されているのtable_1)すぐに2つのテーブルにデータを挿入する

loginDetails

ログインID(PK)< - コードに示す自動インクリメント

パスワード

memberDetails(table_2 )

MEMBERID(PK)< - 自動インクリメント

ログインID(FK)

これらは私がこれまでのところ、しかしmemberDetailsテーブル内のログインIDは常に0 ,:

PHPコードでいるコードです

$Query = "INSERT INTO $table_1 VALUES (NULL, 
    '".$formValue['username']."', 
    '".$formValue['password']."')"; 
if (mysqli_query($Link, $Query)) { 
     $lastID = mysql_insert_id(); 
     $Query2 = "INSERT INTO $table_2 VALUES (NULL, 
     '".$lastID."')"; 
     if (mysqli_query($Link, $Query2)) { 
      $message = "You've sucessfully created the account!"; 
      echo json_encode(array('success'=>'true', 'action'=>'login','html'=>$message, 'console.log'=>$Query)); 
     } 
     else { 
      $message = "Error occur in query2"; 
      echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query)); 
     } 
    } 
    else { 
     $message = "Error in query1"; 
     echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query)); 
    } 

この問題を解決できるのであれば、私はすでに3泊で苦労しています。乾杯。

+0

mysql_insert_idの代わりにmysqli_insert_id($ link)を使用してください。 –

+0

@MuntashirAkon私はこれを試してみましたが、それは働いていません:( –

+0

@RyanVincentそれは、後で 'staffDetails'という別のテーブルを挿入しようとしているためです。** loginDetails * *テーブル –

答えて

0

クエリを配列に配置できます。配列をループします。エラーが発生した場合は、スクリプトを終了します。

$myQueries = array(`"INSERT INTO $table_1 VALUES (NULL, 
'".$formValue['username'].", 
'".$formValue['password']."')", 
    "INSERT INTO $table_2 VALUES (NULL, 
    '".$lastID."')" 
)`; 

for($i = 0; $i < count($myQueries); $i++){ 
    if (mysqli_query($Link, $myQueries[$i])) { 
      $lastID = mysql_insert_id(); 
      $message = "You've sucessfully created the account!"; 
      echo json_encode(array('success'=>'true', 
      'action'=>'login', 
       'html'=>$message, 
       'console.log'=>$Query)); 
    } 
    else { 
     $message = "Error occur in query[$i]"; 
     echo json_encode(array('action'=>'error', 
     'html'=>$message,     
     'console.log'=>$Query)); 
     exit; // stops the next query 
    } 
    } 
}