The tables are Accounts with A_ID (PRIMARY KEY), Username, Password and Messages with M_ID (PRIMARY KEY), Message, A_ID (FOREIGN KEY)
When a person sends a message I am using a SELECT statement to get the person's A_ID where their username = their username and then INSERT it into the table.
The full code is in the Paste below, it is quite messy, please forgive me for that. I'm working on a much cleaner version but I have to get this vital part first.
Where I am really stuck is here ¬
if (isset($_POST['SendMessage'])) {
$GetAID = "SELECT A_ID FROM Accounts WHERE Username='$CookieValue'";
$ResultAID = $Connect->query($GetAID);
echo $ResultAID;
$Message = htmlspecialchars($_POST['Message']);
$MessageSQL = "INSERT INTO Messages (M_ID, Message, A_ID) VALUES ('', '$Message', '$ResultAID')";
if ($Connect->query($MessageSQL) === TRUE) {
echo "Message Sent<BR/>";
} else {
echo "Error Sending Message<BR/>";
}
}
My question is how do I put the A_ID into a variable and then INSERT it into the Messages table as the FOREIGN KEY to Accounts table's A_ID PRIMARY KEY?
The Foreign Key requirement has to be handled on the SQL server. You will need to set up a foreign key restraint.
Inserting the variable is easy.
$MessageSQL = "INSERT INTO Messages (M_ID, Message, A_ID) VALUES ('', '".$Message."', '".$ResultAID['A_ID']."')";
$SQL = "INSERT INTO Accounts (A_ID, Username, Password) VALUES ('', '$Username', '$PasswordHash')";
$Result = mysqli_query($Connect, $SQL);
$GET_last_ID = mysqli_insert_id($con);
$MessageSQL = "INSERT INTO Messages (M_ID, Message, A_ID) VALUES ('', '$Message', '$GET_last_ID')";
just add the $GET_last_ID = mysqli_insert_id($Connect);
below mysqli_query
and insert the variable $GET_last_ID
to the next table. just like u see above. the code $GET_last_ID = mysqli_insert_id($Connect);
will get the lastes inserted primary key id.
hope this help you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.