Hello everyone. I am trying to write a quiz for a site. Questions are in multiple choice, true/false, fill in the blank etc. The example questions i have can be seen below.

I'm trying to plan how am I going to code this. I was thinking of having a table with two columns one with questions and one with answers. The part that troubles me is that tutors should be able to upload quizzes in the example format given below. The upload function is not a problem as I already have this implemented this to upload files to registered students pages.

Could anyone give me some suggestions as where to start with this? I just want to know how you guys would approach this task bearing in mind the tutor being able to upload the quizzes in the below format.

Many thanks in advance
James

`Only digital signals can be used to convey information in the communications environment.

False

True

`The greater the bandwidth of the signal the greater its information carrying capacity.

True

False

`Guided media, also called wireless, provide a physical means for guiding electromagnetic waves  through seawater.

False

True

`A major problem in designing a communications facility is transmission impairment.

True

False

`In full-duplex operation both stations may transmit, but only one at a time.

False

True

`A digital signal is one in which the signal intensity maintains a constant level for some period of time and then abruptly changes to another constant level.

True

False

`The frequency is the rate at which the signal repeats.

True

False

`The sine wave is the fundamental aperiodic signal.

False

True

`Analog signals suffer more from attenuation than do digital signals.

False

True

`For any given medium, the greater the bandwidth transmitted, the greater the cost.

True

False

`There is not a direct relationship between data rate and bandwidth.

False

True

`A familiar example of analog data is audio, which, in the form of acoustic sound waves, can be perceived directly by human beings.

True

False

`The advantages of digital signaling are that it is generally cheaper than analog signaling and is less susceptible to noise interference.

True

False

`An analog signal can be transmitted only a limited distance before attenuation, noise, and other impairments endanger the integrity of the data.

False

True

`Delay distortion occurs because the velocity of propagation of a signal through a guided medium varies with frequency.

True

False

`A key parameter that characterizes any electromagnetic signal is ~text~, which is the width of the range of frequencies that comprises the signal. 

bandwidth   

analog  

digital  

wavelength 

`In ~text~ transmission signals are transmitted in only one direction; one station is the transmitter and the other is the receiver. 

simplex  

half duplex  

multipoint  

full duplex  

`The term ~text~ is used to refer to the transmission path between two devices in which signals propagate directly from transmitter to receiver with no intermediate devices other than amplifiers or repeaters used to increase signal strength. 

direct link 

unguided media  

wireless  

guided 

`A guided transmission medium is ~text~ if it provides a direct link between two devices and those are the only two devices sharing the medium. 

point to point  

wireless  

multipoint  

simplex  

`A(n) ~text~ signal is a continuously varying electromagnetic wave that may be propagated over a variety of media, depending on spectrum.  Examples are wire media and fiber optic cable. 

analog 

aperiodic  

digital  

periodic  

`The ~text~ is the maximum value or strength of the signal over time, typically this value is measured in volts. 

peak amplitude 

frequency  

phase  

period  

`The ~text~ of a signal is the distance occupied by a single cycle. 

wavelength  

amplitude  

frequency  

bandwidth 

`The ~text~ of a signal is the range of frequencies that it contains. 

spectrum   

bandwidth  

effective bandwidth  

wavelength 

`A ~text~ signal is a sequence of voltage pulses that may be transmitted over a wire medium. 

digital  

text  

analog  

audio  

`The communication of data by the propagation and processing of signals is ~text~. 

transmission 

signaling  

interlacing  

effective bandwidth 

`An example of digital data is ~text~ or character strings. 

text  

video  

audio  

interlaced  

`_~text~ is generated by terminals, computers, and other data processing equipment and then converted into digital voltage pulses for transmissions. 

Binary data  

Text  

Voice  

Audio  

`A reduction in strength is _~text~. 

attenuation

interlacing  

delay distortion  

pulsing 

`The rate in bits per second at which data can be communicated is the  ~text~. 

data rate

analog transmission  

channel capacity  

digital transmission  

`When signals at different frequencies share the same transmission medium the result may be ~text~ noise. 

intermodulation  

crosstalk  

white  

impulse 

`The designer of a communications facility must deal with four factors: the data rate that is used for digital information, the amount of noise and other impairments, the level of error rate that is acceptable, and the ~text~ of the signal. 

bandwidth 

`Twisted pair, coaxial cable and optical fiber are examples of ~text~ media. 

guided 

`In a ~text~ guided configuration more than two devices share the same medium. 

multipoint 

`The simplest sort of signal is a _~text~ signal, in which the same signal pattern repeats over time. 

periodic  

`The ~text~ bandwidth of a signal is the width of the spectrum. 

absolute 

`The ~text~ bandwidth is the band where most of the signal energy is concentrated. 

effective  

`A technique known as ~text~ is used to provide a flicker free image without increasing the bandwidth requirement. 

interlacing 

`A means of transmitting analog signals without regard to their content is ~text~ transmission. 

analog  

`To achieve greater distances in digital transmissions ~text~ are used. 

repeaters 

`Thermal noise is also referred to as  ~text~ noise. 

white  

`~text~ noise is noncontinuous, consisting of irregular pulses or noise spikes of short duration and of relatively high amplitude.  It is generated from a variety of causes, such as lightning, and faults and flaws in the communications system. 

Impulse 

`The maximum rate at which data can be transmitted over a given communication path under given conditions is referred to as the ~text~. 

channel capacity  

`The ratio of the power in a signal to the power contained in the noise that is present at a particular point in the transmission is the ~text~ ratio. 

signal-to-noise

`~text~ noise is due to thermal agitation of electrons.  It is present in all electronic devices and transmission media and is a function of temperature. 

Thermal  

`Because of delay distortion some of the signal components of one bit position will spill over into other bit positions causing ~text~ interference, which is a major limitation to maximum bit rate over a transmission channel. 

intersymbol

If you main objective is to get something working quickly, then I'd start with a search to see what open source solutions are available.
http://tinyurl.com/42aebds

Even if it is homework, looking at existing systems will still give you a head start.

i dont just want code and to copy someone elses system. At the moment, I'm just trying to gather ideas and ask people how they would go about it.

i've noticed that every question starts with a backtick and that the answer is always the first choice after the question. I think this would be of some use using a delimiter to work out where the questions begin and end in the file. Does this sound about right??

Member Avatar for diafol

Just some thoughts. I have built a few of these myself in the past, varying in complexity. If you want the tutor to upload like you said the stuff below will be of no value.

QUESTIONS
q_id:       (PK autoincrement)
q_type_id:  (tinyint for FK on: multiple choice, true/false, blank_fill, order, etc)
question:   (blob or text - to hold any type of data, including images - could be html)
topic_id:   (tinyint for FK on topic table)
answers:    (text = can be any format e.g. delimited for multiple choice, etc) 
marks:      (tinyint)
correct:    (text = could be any format, e.g. multiple choice - position, etc - could also be delimited) 

STUDENT
student_id: etc etc etc (+ all the usual fields)

TESTS
test_id:           PK
test_title:        varchar/255 test title 
test_active:       tinyint (0/1) 'takeable'?
test_group:        optional - only certain student groups [this may be better in its own table]
test_description:  text
test_open_date:    date - do not allow test to be taken before this date
test_close_date:   date - do not allow test to be taken beyond this date
test_retake:       tinyint (0/1) retake or not

TEST_QUESTIONS
tq_id:             PK (optional)
test_id:           FK
q_id:              FK
q_label:           optional
q_order:           optional, but useful for reordering without messing with PK

TEST_RESULTS
tr_id:             PK (optional)
tq_id:             FK (or FK on both test_id and q_id)
student_id:        FK
ans:               appropriate datatype for student's answer - useful for questions that require manual marking
score:             tinyint

TEST_SUMMARIES
ts_id:             PK optional
test_id:           FK
student_id:        FK
total:             int (could be calcualted as a raw mark, % etc)

Just off the top of my head - depends how complicated you want it to be. It's vitally important that you normalize the data as much as possible.

thanks for that ardav, unfortunately its vital that the tutor must be able to upload. As this is for an assignment, I really want to achieve the top mark.

I've been assured by the tutor that there will be no marks for normalisation and even been encouraged to use a flat file. I do agree with you though, normalisation would normally be a must.

I'm just a bit bamboozled as where to start with it all?

EDIT: P.S I don't think I would need many fields or it to be too advanced., I have a table called users which contains student details etc. I was just going to add testresult1, testresult2, etc... to the table users and another table called quiz which would contain different questions and answers??

Hope this makes sense, it's starting to get late here in the u.k :S

Member Avatar for diafol

regex would be one way to deal with upload. I think delimiting would be messy, depending on the variety of question types. I'm sorry but regex / preg leaves me cold. OK,

you have the format:

`: to start a new question

question types to date: multiple choice (1st answer correct, always 4 options); true/false (1st answer correct, always both options); missing word (single answer)

Step 1
You could explode() on ` - so that you get an array of questions along with attached answers.

Step 2
Explode each question on a new line - reject empty lines and keep the rest - this will give you an array of answers (1 for text, 2 for boolean, 4 for multiple choice). Ensure that these are linked to the question as part of a multidimensional array.

Step 3
Add a question_type key to each parent level to help with the SQL.


So, you should end up with:

Array
[0] => array('q' = "the text of the first question here...",'ans' => array('answer1','answer2','answer3','answer4'),'type'='mchoice'),
[1] => array('q' = "the text of the second question here...",'ans' => array('thisisananswer'),'type'='text'),
[2] => array('q' = "the text of the third question here...",'ans' => array(true,false),'type'='bool'),
[3] => array('q' = "the text of the fourth question here...",'ans' => array(false,true),'type'='bool')
<?php


$questions = explode("`", file_get_contents("quiz.txt")); //taking string and placing it an array. 

$mystring = implode("",$questions); //taking array and placing it in string

$answers = explode(".",$mystring); //creates an array called answers


print_r($questions);
print_r($answers);

?>

Okay, i think i'm understanding. The problem I was having was that once I exploded the file, the file was converted to an array and consequently I could not use another delimiter to seperate the answers.

Using the above code, i get two arrays. One which has the question at the beginning of each array item and one which has the answer.

Is this correct to what you were saying?

thanks again

Member Avatar for diafol

will get back to you...

as this is becoming incredibly difficult, i'm going to assume that editing of the original quiz file can be edited providing the questions are still there. I'm thinking of maybe seperating the original quiz in to three files. Each file would then consist of one type of questions.

E,g, quiz 1 part 1 - multiplechoice

quiz 1 part 2 - true/false

Would this maybe make things easier do you think?

Member Avatar for diafol

Here we go...

Place the text (all that stuff from your teacher) into the variable $txt.

$lumps = explode("`",$txt);
array_shift($lumps);

foreach($lumps as $lump){
	$items = explode("\n",$lump);
	$x = 0;
	if(isset($answers))unset($answers);
	foreach($items as $item){
		if($x == 0){
			$question = $item;
		}elseif(trim($item) != ""){
			$answers[] = $item;
		}
		$x++;
	}
	switch(count($answers)){
		case 1:
			$type = "text";
			break;
		case 2:
			$type = "boolean";
			break;
		case 4:
			$type = "mchoice";
			break;		
	}
	$qarray[] = array("question" => $question, "type" => $type, "answers" => $answers);
}

All the data is now nicely packages into an array, ready to be inserted into a DB. You may want to implode the answers with a suitable delimiter if you want the whole lot in one field - your choice.

i'm sorry but i don't quite understand the code, Does each array element contain the question, its type, and then the answer.

What should I be echoing out to see these values?

Member Avatar for diafol

OK

The $qarray holds everything.

print_r($qarray) gives this:-

Array ( [0] => Array ( [question] => Only digital signals can be used to convey information in the communications environment. [type] => boolean [answers] => Array ( [0] => False [1] => True ) ) [1] => Array ( [question] => The greater the bandwidth of the signal the greater its information carrying capacity. [type] => boolean [answers] => Array ( [0] => True [1] => False ) ) [2] => Array ( [question] => Guided media, also called wireless, provide a physical means for guiding electromagnetic waves through seawater. [type] => boolean [answers] => Array ( [0] => False [1] => True ) ) [3] => Array ( [question] => A major problem in designing a communications facility is transmission impairment. [type] => boolean [answers] => Array ( [0] => True [1] => False ) ) [4] => Array ( [question] => In full-duplex operation both stations may transmit, but only one at a time. [type] => boolean [answers] => Array ( [0] => False [1] => True ) ) [5] => Array ( [question] => A digital signal is one in which the signal intensity maintains a constant level for some period of time and then abruptly changes to another constant level. [type] => boolean [answers] => Array ( [0] => True [1] => False ) ) [6] => Array ( [question] => The frequency is the rate at which the signal repeats. [type] => boolean [answers] => Array ( [0] => True [1] => False ) )...

Now you can load it into a DB:

foreach($qarray as $q){
 //build up an insert string ($insert)
}

run query using the insert string.

Like I said though, you'll proabably need to store answers as a single item with a delimiter, like "|".

Member Avatar for diafol

Here we go again:

$lumps = explode("`",$txt);
array_shift($lumps);

foreach($lumps as $lump){
	$items = explode("\n",$lump);
	$x = 0;
	if(isset($answers))unset($answers);
	foreach($items as $item){
		if($x == 0){
			$question = $item;
		}elseif(trim($item) != ""){
			$answers[] = $item;
		}
		$x++;
	}
	switch(count($answers)){
		case 1:
			$type = "text";
			break;
		case 2:
			$type = "boolean";
			break;
		case 4:
			$type = "mchoice";
			break;		
	}
	$ans = implode("|",$answers); //ADD THIS
	$qarray[] = array("question" => $question, "type" => $type, "answers" => $ans); //CHANGE THIS
}

$sql="";
foreach($qarray as $q){
	$sql .= ",(\"{$q['question']}\",\"{$q['answers']}\",\"{$q['type']}\")";
}
$sql = substr($sql,1);

$r = mysql_query("INSERT INTO table (`question`,`answers`,`type`) VALUES $sql");

NOT tested.

O.k, i've added my sql connection and changed the insert query to associate with my table. I'm still not getting anything added to the database though.

<?php

$txt = file_get_contents("quiz.txt");

$lumps = explode("`",$txt);
array_shift($lumps);

foreach($lumps as $lump){
	$items = explode("\n",$lump);
	$x = 0;
	if(isset($answers))unset($answers);
	foreach($items as $item){
		if($x == 0){
			$question = $item;
		}elseif(trim($item) != ""){
			$answers[] = $item;
		}
		$x++;
	}
	switch(count($answers)){
		case 1:
			$type = "text";
			break;
		case 2:
			$type = "boolean";
			break;
		case 4:
			$type = "mchoice";
			break;		
	}
	$ans = implode("|",$answers); //ADD THIS
	$qarray[] = array("question" => $question, "type" => $type, "answers" => $ans); //CHANGE THIS
}

$connect = mysql_connect("localhost","root","root") or die("couldn't connect");
mysql_select_db("login") or die ("couldn't find db");
$sql="";
foreach($qarray as $q){
	$sql .= ",({$q['question']},{$q['answers']},{$q['type']})";
}
$sql = substr($sql,1);


$r = mysql_query("INSERT INTO questions (`question`,`answer`,`type`) VALUES $sql");
?>

I've also tried moving the query and the substring line in to the foreach loop as mentioned in a previous post. This has not worked either. I know this is getting so close to the end as well. I just can feel it.

Was i meant to put something in here?

$sql="";
Member Avatar for diafol

> Was i meant to put something in here? NO.

Before this:

$r = mysql_query("INSERT INTO questions (`question`,`answer`,`type`) VALUES $sql");

Put this:

echo "INSERT INTO questions (`question`,`answer`,`type`) VALUES $sql";

see what you get. If it makes sense, copy it from the screen and paste it into
the SQL window of phpMySQL or to the query pane of your favourite MySQL GUI. See if there are any errors.

I'm assuming you have a table structure as indicated in the query?
questions table
id (PK, autoincrement) | question (text) | answer (text)| type (varchar 7)

after echoing the contents of the query everything seems to look o.k.
This is the error i recieve when trying to query through phpmyadmin.

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'digital signals can be used to convey information in the communications environm' at line 1

this is the first part of the printed query.

INSERT INTO questions (`question`,`answer`,`type`) VALUES (Only digital signals can be used to convey information in the communications environment. ,False |True ,boolean),(The greater the bandwidth of the signal the greater its information carrying capacity. ,True |False ,boolean),(Guided media, also called wireless, provide a physical means for guiding electromagnetic waves through seawater. ,False |True ,boolean),(A major problem in designing a communications facility is transmission impairment. ,True |False ,boolean)(
Member Avatar for diafol

This is the problem line:

$sql .= ",({$q['question']},{$q['answers']},{$q['type']})";

It should read:

$sql .= ",(\"{$q['question']}\",\"{$q['answers']}\",\"{$q['type']}\")";

You must have copied my draft post. I wasn't quick enough to edit it!

Also:

}elseif(trim($item) != ""){
			$answers[] = $item;
		}

would be better like this:

}elseif(trim($item) != ""){
			$answers[] = trim($item);
		}

OMG, it works, Thank you so much for your persistence with this. Tomorrow i'm going to have a look at developing the front end of the quiz and retrieving the data from the database and using it in the quiz. Should hopefully not be as hard as that was!.

Unfortunately, i've just found a snake in my kitchen which i'm going to be focussing on now. Not what i need at all.

Once again, thanks so much.

Member Avatar for diafol

Ok good luck. That wasn't hard. That was fun.

EDIT:: Deleted this for asking something stupid!

Okay, so i have my true and false options showing correctly and i've also echo'd out the answer underneath each question for reference.

<?php

$connection = mysql_connect("localhost","root","root") or die("couldn't connect");
$select = mysql_select_db("login") or die ("cannot select database!");

$query = mysql_query("SELECT * FROM questions");

$numrows = mysql_num_rows($query);

if ($numrows!=0)
{
   //code to login
   while($row = mysql_fetch_assoc($query))
   {
   $dbquestion = $row['question'];
   $dbanswer = $row['answer'];
   $dbtype = $row['type'];
   $correctanswer =  explode('|',"$dbanswer");

   

switch($dbtype){
case "mchoice":
echo"<br/>"; echo $dbquestion; echo"<br/>";
break;

case "boolean":
echo"<br/>"; echo $dbquestion; echo"<br/>";
echo $correctanswer[0];

//display radio buttons

?> 
<form action="" method="POST">
True
<input name="question" type="radio" value= "True" /> 

False 
<input name="question" type="radio" value= "False" />
</form> 


<?php
break;

case "text":
echo"<br/>"; echo $dbquestion; echo"<br/>";
//display text box
break;
}
   }
}

?>

Would I use a seperate page to process the answers. I'm not sure how this works, With my registraion page the values are posted and then sent to the database. With something like this i'm going to need something like

if($radiovalue == $correctanswer[0]); //if the value of the radio button is equal to the correct answer
{
   $score = $score+1
}

else
{
$score = $score

I'm not sure how i would post all the individual values for something like the above comparison?? Any suggestions would be great.

Many thanks

Member Avatar for diafol

Ok a few ideas:

output:

1) extract data from DB (as is)

2) based on question type, create the answer form:

radiobuttons for boolean and mchoice
textbox for text

you only need to explode on mchoice.


because your answers for mchoice all start with the correct answer, you need to randomize the order in which they appear. Make the value attribute equal to the order in which they appear in the DB (0,1,2,3). Then run the randomizer.


3) place a hidden field holding the question id and possibly a hidden field for type (useful for determining how to process the answers later on). The id could be held by session variables.


You now have a choice - send to the same page or to a different page. There are pros and cons of each:

Same page: easy to code; liable to reload/refresh causing resubmission of form.

Diff page: more difficult to code as data has to be sent back to the form page. This is usually done with sessions; no problem when page refreshed/reloaded.

I would always go with a diff page, but choice is yours.

So, get the question type, the question id and answer from the $_POST variable.

Check the answer against the DB, keep a running total. I suggest using sessions for this.

Now again you have a choice - do you store the answer for feedback purposes or do you just store the total?

It's quite useful to see the breakdown per question for the tutor.

okay, with the hidden items put in my code loks like this.

switch($dbtype){
case "mchoice":
echo"<br/>"; echo $dbquestion; echo"<br/>";
break;

case "boolean":
echo"<br/>"; echo $dbquestion; echo"<br/>";
echo $correctanswer[0];

//display radio buttons

?> 
<form name="boolean" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
True
<input name="question" type="radio" value= "True" /> 
False 
<input name="question" type="radio" value= "False" />
<input name="id" input type="hidden" value="$dbid" />
<input name="type" input type="hidden" value="$dbtype" />


</form> 

<?php
break;

case "text":
echo"<br/>"; echo $dbquestion; echo"<br/>";
//display text box
break;
}
	}
}

?>

Like i said, Im only trying to analyse the true and false questions in the moment. I don't understand how to submit the form with all the variables held.

At the moment, the code comes across a question of boolean and outputs the true and false inputs. I don't understand how the comparison works. How does the code work so that when submit is pressed, the users answers are compared with the input?? I'm really confused. Do I have a submit button linked to multiple forms??

When using this code, i end up with a submit button for each question. If i select an answer for one of the questions, it applies the answer to every question. Is there any way of storring the $_POST variable of each question. I'm sorry if I'm being persistent with this, just really want to get it working to some extent.

Once again, thanks for the time you've spent with this.

switch($dbtype){
case "mchoice":
echo"<br/>"; echo $dbquestion; echo"<br/>";
break;

case "boolean":
echo"<br/>"; echo $dbquestion; echo"<br/>";
echo $correctanswer[0];
?> 
<form>
<form name="boolean" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
True
<input name="question" type="radio" value= "True" /> 
False 
<input name="question" type="radio" value= "False" />
<input name="id" input type="hidden" value="<?php $dbid ?>" />
<input type="submit" name="submit" id="submit" value="Submit" />

<?php
echo "The answer submitted was ";
echo  $_POST['question'];
?>
</form>
<?php
break;

case "text":
echo"<br/>"; echo $dbquestion; echo"<br/>";
//display text box
break;
}
}
}
?>
Member Avatar for diafol

No problem.I'm on holiday for a week from tomorrow so any help I can give will be tonight. I've got a few hospital appointments today so after 1700 GMT.

Think about all the questions to which you need answers and post them by the time above. I have a solution in my head, but giving you a solution will not help you develop your skills.

echo $correctanswer[0];

I don't understand why you've echoed this though. For testing?

OK so I assume you've got all the questions and answers on one page and you want a submit button at the end of each answer.

As I stated previously, your problem is that you're posting to the same page. Using sessions will make things considerably easier.

In fact using ajax would make it easier, but one step at a time, eh?

K, have to go, will speak to you later, unless somebody else feels like lending a hand?

hello, sorry about the delay, I had a job interview as a follow up on the telephone interview during the week and have been busy non-stop.

I decided to process them on the same page as i thought it would be easier to do it that way.
Ideally, I would like all the questions displayed and then one subit button which will process all of the answers.
The problem I'm having at the moment is that I have multiple submit buttons appearing and if i select an answer for one of the questions, it answers all of the questions with that answer.

<input name="question" type="radio" value= "True" /> False <input name="question" type="radio" value= "False" />

I think it may be something to do with that above. Everytime the switch loop runs, it uses the same input name and i think the form does not distinguish is at as a new question.
I think I need some variable in there such as $dbid which will increment everytime the loop is ran. I cannot seem to figure this out though.

Once again, thanks for looking at this and I'm really sorry its so late, hopefully you'll have time to respond.

Many thanks
James

P.S.

echo $correctanswer[0]

was just used for testing. Forgot to take it out in the edit.

Member Avatar for diafol
<input name="question" type="radio" value= "False" />

This needs some sort of id attached to the name:

<input name="question_1" type="radio" value= "False" />
<input name="question_1" type="radio" value= "True" />

then

<input name="question_2" type="radio" value= "False" />
<input name="question_2" type="radio" value= "True" />

You can build this up with php in your loop. Something like:

<input name="question_{$row['id']}" type="radio" value= "True" />

just to say that I have everything working now and I'm able to upload the files to a database, have them placed in a quiz, and then have the users score marked at the end.

Member Avatar for diafol

Just back today - great news jimmy. Come back if you hit a snag.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.