I’m writing a very simple PHP script for surveys. At this time, it can only handle one survey at a time. The database schema looks like this:
table 1: questions
primary key: question_id
second field: question
table 2: answers
primary key: answer_id
second field: answer
foreign key: question_id
I have an admin section in this script that allows me to add one question at a time. I’ve also made it possible to add a variable number of answers to each question. I’m having trouble with two things:
- How can I make sure that the variable number of answers being added all have foreign keys that link to the correct question? Do I need to
INSERTthe question, thenSELECTit to find its ID, thenINSERTthe answers? I feel like there should be a better way to do it. - What’s the best way to accomplish what I’m trying to do? Is my database schema trash? Do I need a bunch of queries to get what I want done? I’m not fluent in SQL :/
Thanks!
Gerard
You first need to insert the question. Then you can use
$questionId = mysql_insert_id();, this gives you the generated id of the last insert. Now you can use that to insert your answers properly.