1

hi am building a quiz system and basically i have my questions in an array called $questions and answers in an array $answers i have created an interface in html php to add data questions and answers into this arrays

$question1 = $_POST['question1'];
$question2 = $_POST['question2'];

$ans1 = $_POST['ans1'];
$ans2 = $_POST['ans2'];

$questions = array();

array_push($questions,$question1,$question2);

$answers = array();

array_push($answers,$ans1,$ans2); 

so to insert this values in a database this is what i do

$quest_count = count($questions);

for ($i=0;$i<=$quest_count;$i++)
{
  $query = "INSERT INTO quiz (question,answer) VALUES ('$questions[$i]','$answers[$i]')";
  $result = mysql_query($query);
}

so my problem is this the for loop should add two rows in the database since the questions array contains two values question1 and question2 but it only adds one row. can anyone help me out on this am sure its ('$questions[$i]','$answers[$i]') part that has a problem.

thanks

1
  • You should get used to properly concatenate variables, either use {$questions[$i]} or ". $questions[$i] . " Commented Oct 17, 2013 at 7:06

3 Answers 3

1

You're using the <= operator in your loop.

Change it to just less than:

for ($i=0;$i<$quest_count;$i++)
{
  $query = "INSERT INTO quiz (question,answer) VALUES ('$questions[$i]','$answers[$i]')";
  $result = mysql_query($query);
}

Also, make sure you properly sanitise your input strings.

Sign up to request clarification or add additional context in comments.

1 Comment

You just copied from the question but this is not how you put variables, especially array elements into a string.
0

Please use < than using <= in the for loop, this will ensure that the loop runs twice or the exact of count of question array.

Comments

0

Try this:

Here no need to count array values & for loop. Instead use foreach loop.

Here is the solution:

foreach ($questions as $key1 => $que, $answers as $key2 => $ans)
{
  $query = "INSERT INTO quiz (question,answer) VALUES ('$que','$ans')";
  $result = mysql_query($query);
}

- Thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.