我想知道如何将从HTML表单中检索的值插入到2个表中,loginDetails和memberDetails。
loginDetails(代码中显示了table_1)
loginID(PK)
用户名
密码
memberDetails(代码中显示了table_2)
memberID(PK)
loginID(FK)
这些是我到目前为止的代码,但是memberDetails表中的loginID始终为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个晚上。干杯。
最佳答案
您可以将查询放置在数组中。遍历数组。如果发生错误,请退出脚本。
$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
}
}
}