I am stuck on inserting the data into mysql via php.

Its a foreach method and I am just stuck

include '../Database/take_an_exam.php';
$intNum = 1;
$intnumber = 1;
while( $info = mysql_fetch_array( $sqll )){   
 echo "<input type='hidden' name=\"Que_ID\" value=\"{$info['Que_ID']}\" /> "; 
 echo " $intNum, {$info['Que_Question']} <br />\n";  
  $intNum++;  
for ($i =1; $i < 5; $i++) {   
 echo "<input type=\"checkbox\" name=\"choice[{$info['Que_ID']}.$i][]\" />{$info['Que_Choice'.$i]}<br />\n";   
 $intnumber++; } }?>
<input type="submit" value="submit" name="submit">

This is my form that can output the Question and its choices.

I am echoing this on to the next page, the code is shown below

<?PHPsession_start();
$name= $_SESSION['username1'];
echo "User ID: $name <br/>";
$gender = $_POST["choice"];
$que_ID = $_POST["Que_ID"];
foreach ($gender as $key => $array) {  	
if($array)	{ 
  $val=1; }  
//echo "Question ID and the choice ID:$key. Value is:.$val <br />\n"; 
$well = array(floor($key), substr(strstr($key, '.'), 1)); //$well = array(floor($key), $key - floor($key));

Now, instead of echoing. I just want to add this to mysql.

The layout of my sql is Que_ID, Ans_Choice1, Ans_Choice2, Ans_Choice3, Ans_Choice4, Use_ID

When I echo my php my outcome is

User ID: 2
Question ID= 1 Choice 1
Question ID= 2 Choice 3
Question ID= 3 Choice 4
Question ID= 4 Choice 1

Recommended Answers

All 17 Replies

Hi xxreenaxx1, first off: a code that isn't indented properly is hard to read. Please help us help you, and write code as

if (...) {
  ...
  ...
}

and not

if (...)    {
...
     .... }

Anyway, this is how you insert values into a database:

mysql_query("INSERT INTO youTableName (Que_ID, Ans_Choice1, Ans_Choice2, Ans_Choice3, Ans_Choice4, Use_ID) VALUES (numeric_value, 'string_value', 'string_value', 'string_value', 'string_value', numeric_value)");

This doesn't protect you against SQL injection though. You should use mysql_real_escape_string() for each value you pass to MySQL. The code will get cluttered but still better than having your website hacked. The ultimate solution is to use some database wrapper that uses some kind of a query template and escapes the values for you. Try Dibi for instance (http://dibiphp.com/)

Sorry about my code

I can do the INSERT but since I am using checkbox to retrieve these information and wants to INSERT the checked box as 1 in to my database and the one that is not checked is 0. Not sure how to do this.

while( $info = mysql_fetch_array( $sqll )){  
		echo "<input type='hidden' name=\"Que_ID\" value=\"{$info['Que_ID']}\" /> ";
		echo " $intNum, {$info['Que_Question']} <br />\n"; 
		$intNum++;
 
	for ($i =1; $i < 5; $i++) {  
 
		echo "<input type=\"checkbox\" name=\"choice[{$info['Que_ID']}.$i][]\" />{$info['Que_Choice'.$i]}<br />\n";  
		$intnumber++;
	}
	}
include '../studentsql/completed.php';
session_start();
$gender = $_POST["choice"];
$que_ID = $_POST["Que_ID"];

	if($isset($_POST['submit']){
		foreach ($gender as $key => $array) {  
		if($array)
			{  
			$val=1;
			}
			$well = array(floor($key), substr(strstr($key, '.'), 1));
			$lop= completed($Answer1, $Answer2, $Answer3, $Answer4, $well[0], $_SESSION['username1']);
	}

If I get it right, your issue is that unchecked checkboxes don't submit so you never receive a value if the checkbox is unchecked, right?

I suggest not browsing the submitted $_POST array but use the same loop you used for building the checkboxes (MySQL query result). Then for each option, see if a value exists in $_POST - it would mean a checked checkbox. If the value is missing then it means the checkbox was not checked.

$choice1 = $_POST["choice1"];
$choice2 = $_POST["choice2"];
$choice3 = $_POST["choice3"];
$choice4 = $_POST["choice4"];

while($info = mysql_fetch_array( $sqll ))
	{
	
		echo "{$info['Que_ID']} <br />\n";
		
//$que_ID = $_POST["Que_ID"];

	//if($isset($_POST['submit'])){
		foreach ($choice1 as $key => $array) {  
		if($array)
			{  
			$val=1;
			}
		
		foreach ($choice2 as $choice => $what){
		if($what)
			{
			$what=1;
			}

would it be something like this. I am not a pro in PHP or mysql. So help me out :D

a little off topic but a few suggestions
session_start(); always go at the top of the page right after the opening tag. or you will run into some issue about headers already being sent

also you can clean this up with single quotes instead of escaping all of your double

original
echo "<input type='hidden' name=\"Que_ID\" value=\"{$info}\" /> ";

cleaner
echo '<input type="hidden" name="Que_ID" value="'.$info.'" /> ';

as you can see i used '.$info.' this basically means that this is php that needs to be run (typically variables nothing like an if statement).

so ' end string . adding php $info php variable . done with php ' return to string.

now you dont have to do it this way but i find it alot easier to read then escaping all of your double quotes. of course is it was javascript in there you would have to escape the single quotes

Thank you for your advice. Will try that but first I just wanted to get my program to work then I will sort these silly mistakes I made. Thank you though

I can echo the choices for the question ID. Now I just want to enter these into mysql

$choice = $_POST["choice"];
	while($info = mysql_fetch_array( $sqll ))
	{
	
	$questionid = $info['Que_ID'];
	
		echo "question id: $questionid <br />\n";
		

		foreach ($_POST["choice"] as $question => $answer) 
		{ 

		if($answer == NULL) 
		{ 
		$val=0; 
		}
			else{
			 $val = 1;
			 }

		echo "choice id: $question. value: $val <br />";
		$lop= completed($choice1, $choice2, $choice3, $choice4, $questionid, $_SESSION['username1']);

		}
	}

My echo message will tell me which choice has been selected. According to this I just want to INSERT this into mysql. Eg: If the echo was:

choice1 value1
choice2 value1

then $choice1 should INSERT 1 AND $choice2 should INSERT 1 but $choice3 and $choice4 should be 0. If there is nothing is selected it will automatically INSERT 0.

xxreenaxx1, you're trying to read $_POST["choice1"] but that's not what you submit. You named your checkboxes choice[{$info}.$i][] so you'll get something like
$_POST[0]
$_POST[0]
$_POST[0]
$_POST[0]
(example for Que_ID 12; only if all checkboxes checked)

Try var_export($_POST); It will tell you exactly what has been submitted.

I guess you could just name the checkboxes choice[{$info}][$i] which will submit
$_POST[12][1]
$_POST[12][2]
$_POST[12][3]
$_POST[12][4]
which is easier to use.

What I meant by my previous post was something like (using the new naming mentioned above):

mysql_data_seek(sqll, 0);
while($info = mysql_fetch_array( $sqll )) {
  $questionId = $info['Que_ID'];
  $choices = array();
  for ($i =1; $i < 5; $i++) {
    if (empty($_POST['choice'][$questionId ][$i])) {
      $choices[$i] = 0;
    } else {
      $choices[$i] = 1;
    }
  }
  mysql_query("INSERT INTO youTableName (Que_ID, Ans_Choice1, Ans_Choice2, Ans_Choice3, Ans_Choice4, Use_ID) VALUES ($questionId, {$choices[1]}, {$choices[2]}, {$choices[3]}, {$choices[4]}, '".$_SESSION['username1']."')");
}

I don't understand what is the function completed() in your last post but I guess it doesn't matter now.

function completed was a function that I used to INSERT these details into database. I had to adjust few bits but now I got it working. Thank you so much :D

I have a problem with this. I have more then one question and when I complete the first question and the choices for these are entered for all the other question.

eg. Question ID, choice 1 is selected, choice 2 is not selected, choice 3 is not selected, choice 4 is selected

Values for these would be. questionid= 2,choice1= 1,choice2=0,choice3=0,choice4=1

These choice values are repeated for all the other questionid.
so if the question ID was 3 the same choice value as questionid2 will be entered into questionid.

How would I prevent this.

I don't think this would happen with the piece of code I gave you. Could you please attach a complete source code? I will have a look.

It would also help me if you could attach a database dump. Thanks.

I dont know how to attach here.

Click Use Advanced Editor and then Manage Attachments below the editor area under Attach Files.

I dont know how to attach here.

found it

here is the rest :D

Mhm, I expected three files:
- form display page
- submitted choices saving page
- database dump

What are all these files? Please bear in mind that I want to spend like 10 minutes on this so please try not to waste my time.

Sorry, I am using function so splitted these into different files. But I managed to put them together. You will need a conection file. The rest I have uploaded it here.

Student_takeanexam is the form
test_completed is the action
online_examination is the database

Thanks for describing what each file does.

The bug is in Student_Takeanexam.php:

for ($i =1; $i < 5; $i++) {  
 
  echo "<input type=\"checkbox\" name=\"choice[$i][]\" />{$info['Que_Choice'.$i]}<br />\n";  
  $intnumber++;
}

It should be choice[{$info}][$i]

And then in Test_Completed.php:

$questionId = $info['Que_ID'];
$choice = array();
for ($i =1; $i < 5; $i++) {
  if (empty($_POST['choice'][$i])) {

it should again be $_POST[$questionId][$i] (just as I had in my code).

Next time you're getting unexpected values in $_POST try var_export($_POST); It will show you all that has been submitted. In this case, you would notice that you're not submitting unique values for each question.

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.