I have 2 tables relating to a survey. When user answers each set of questions and then click the submit button, it will loop each answer according to the form submitted in order to check within the database first, if the CustomerID and QuestionID have been found, then do the Update. If not found, do the Insert instead.
QUESTIONS table
- QuestionID (PK)
- QuestionText
ANSWERS table
- AnswerID (PK)
- CustomerID (FK)
- QuestionID (FK)
-
AnswerText
<html> .... <form action="/db.php" method="POST"> <?php echo $questiontext[1]; ?><input type="text" name="answer1" id="answer1"> <?php echo $questiontext[2]; ?><input type="text" name="answer2" id="answer2"> <?php echo $questiontext[3]; ?><input type="text" name="answer3" id="answer3"> <?php echo $questiontext[4]; ?><input type="text" name="answer4" id="answer4"> <?php echo $questiontext[5]; ?><input type="text" name="answer5" id="answer5"> <?php echo $questiontext[6]; ?><input type="text" name="answer6" id="answer6"> <input type="submit" name="submit" id="submit" value="Submit"> </form> ... </html>
db.php
<?php
if(isset($_POST['submit'])) {
$cusid = intval($_POST['CustomerID']);
$answer1 = $db->real_escape_string($_POST['answer1']);
$answer2 = $db->real_escape_string($_POST['answer2']);
$answer3 = $db->real_escape_string($_POST['answer3']);
$answer4 = $db->real_escape_string($_POST['answer4']);
$answer5 = $db->real_escape_string($_POST['answer5']);
$answer6 = $db->real_escape_string($_POST['answer6']);
$sql = "INSERT INTO Answers (CustomerID, QuestionID, AnswerText) VALUES
('".$cusid."','".$quesid."','".$answer."')";
$res = $db->query($sql) or die ('Error: ' . mysqli_error($db));
}
?>
My questions are:
- How to update each answer(1-6) one by one and then insert into the database if CustomerID and QuestionID have not been found by using array and SQL query, if found, then just update?
- How could I reference the QuestionID in order to related with AnswerText in HTML and PHP?
This is just an idea for you. Hope you can understand it. Make sure you replace database driven functions with your
$dbobject.