Problem:
I have made a simple form that uses PHP to pass information to my database via a INSERT query. However, every time I run it, it tries to put the information in twice. How can I avoid this?
Explanation:
I first insert the answers, into my answers table, save the AnswerID as a variable. Then do the save with my question table and lastly I use the two saved variables containing the ID's into my question_answers table.
My code:
if (isset($_POST['textinput1']) && !empty($_POST['textinput1'])) { $text1 = mysqli_real_escape_string($conn, $_POST['textinput1']); $text2 = mysqli_real_escape_string($conn, $_POST['textinput2']); $q_text = mysqli_real_escape_string($conn, $_POST['textarea']); $stmt = $conn->prepare("INSERT INTO answers (Answer1Text, Answer2Text) VALUES (?, ?)"); $stmt->bind_param('ss', $text1, $text2); $stmt->execute(); $answerid = $stmt->insert_id; $stmt = $conn->prepare("INSERT INTO question (QuestionText) VALUES (?)"); $stmt->bind_param('s', $q_text); $stmt->execute(); $questionid = $stmt->insert_id; if ($stmt->execute()) { $stmt = $conn->prepare("INSERT INTO question_answers (AnswerID, QuestionID) VALUES (?, ?)"); $stmt->bind_param('ss', $answerid, $questionid); $stmt->execute(); echo "<h2>Dit spørgsmål er nu lagt op på siden!</h2>"; echo "<h3>Tusinde tak for din interesse for SMIL - Skodfri Århus.</h3>"; } else { echo "ERROR: Could not able to execute . " . mysqli_error($conn); } } // close connection mysqli_close($conn); ?> My tables of importance:
question: QuestionID(PK), QuestionText
answers: AnswerID(PK), Answer1Text, Answer2Text
question_answers: QuestionAnswerID(PK), QuestionID(FK), AnswerID(FK)
Ps. I prefer not to use composite unique constraint as a solution.
Also a side-question, should $stmt->insert_id variables be mysqli_real_escape_string?
$stmt->execute()twice. With prepared statements you don't need to be escaping.