Jump to content

Recommended Posts

I am trying to post while loop array. But I dont know how to do this and I used foreach and it works for each array but doesnt loop this. My table has Que_ID, Question, choice1, choice2, choice3 and choice 4. I would like to do something like.. For each Que_id (choice1, choice2, choice3 , choice4), this should be looped for each que_id

 

so far I have

 

$counter = 1;
while( $info = mysql_fetch_array( $sqll ))
//))
{
echo "{$info['Que_ID']} <br />\n";
echo "<input type='hidden' name=\"Que_ID\" value=\"{$info['Que_ID']}\" /> ";
echo "{$info['Que_Question']} <br />\n";
echo "<input type=\"checkbox\" name=\"choice[$counter]\" value=\"{$info['Que_Choice1']}\" /> ";
echo "{$info['Que_Choice1']} <br />\n";
$counter++;
echo "<input type=\"checkbox\" name=\"choice[$counter]\" value=\"{$info['Que_Choice2']}\" /> ";
echo "{$info['Que_Choice2']} <br />\n";
$counter++;
echo "<input type=\"checkbox\" name=\"choice[$counter]\" value=\"{$info['Que_Choice3']}\" /> ";
echo "{$info['Que_Choice3']} <br />\n";
$counter++;
echo "<input type=\"checkbox\" name=\"choice[$counter]\" value=\"{$info['Que_Choice4']}\" /> ";
echo "{$info['Que_Choice4']} <br />\n";

$counter++;

 

How would go on to posting these while loop and display Que_ID and all the choices that are ticked for this que_ID and if its not ticked then its 0.

Link to comment
https://forums.phpfreaks.com/topic/229409-_post-while-loop-array/
Share on other sites

Hi xxreenaxx1,

 

Lets break this down into steps

 

1,) I am assuming $sqll is the result and not the actual query string ? If not make sure you pass the function mysql_fetch_array a result and not the query.

2.) If you want to return the array $info as $info['whateverColumnThisIs'] then you need to make use of the mysql_fetch_assoc and not mysql_fetch_array. using the later would produce $info[aNumber]['whateverColumnThisIs']

3.) Are you accepting more than one answer for each question ? if no then the checkboxes for each question should have the same name i.e. choiceForQueIdX or if you want to accept multiple answers per question you should use choiceForQueIdX[]. I dont understand why you are making use of a counter variable ?

4.) Get back yo me after making some changes to your code and answering these questions and then I can help you further

...2.) If you want to return the array $info as $info['whateverColumnThisIs'] then you need to make use of the mysql_fetch_assoc and not mysql_fetch_array. using the later would produce $info[aNumber]['whateverColumnThisIs']...

You must be getting mixed up with mysql_fetch_row() as mysql_fetch_array() works with both/either field name or relative index number.  So while it does work as $row[0], it also works with $row['fieldName']

 

anyway, I would like to see the whole code related to this as it is, particularly the part where the SQL query is assigned. Also, you have over-complicated your checkbox generation, you don't need the counter, and I would drop the curly braces as well, they are also unneeded.

The curly braces are indeed needed to avoid syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

 

even though they are nested within a double quoted string rather than a single quoted one? :confused: never knew that to happen.  I assume it's an array thing, as I have never actualy tried to echo anything from an array in this manner I was just working under it being the same as if it was a single flat variable. my bad.

Thank you so much for your response

 

@ mhodge_txs

1, yes it is the result

 

<?php

$sql = ("SELECT * FROM user u,question q, test t
WHERE u.Use_ID = '{$_SESSION['username1']}'
    AND t.Sub_ID = '{$_SESSION['ssubject']}' 
AND  q.Tes_ID = t.Tes_ID
AND q.Tes_ID = {$_SESSION['smodule']}")
or die(mysql_error());

echo $sql;

$sqll = mysql_query($sql);

?>

 

2, I do want the $info to return array as choice1 to 4 is repeating. and this is why I created a counter so each time the while loop is process the name of the choice wouldnt be the same. Que_ID=1(choice1,choice2,choice3,choice4) second loop. Que_ID=2(choice5,choice6,choice7,choice8)

3, Yes I am accepting more then one answer. Because I want the name to be different or atleast add one number each time it loops the choices so when I call these choices each will have different value and names.  4, I am not sure what I should change.

 

@Muddy_Funster

 

I have shown my sql query on the top.

 

<html>
<body>
<form action="Test_Completed.php" method="POST">
<?PHP

include '../Database/take_an_exam.php';
//$intNumber = 1;]
$counter = 1;
while( $info = mysql_fetch_assoc( $sqll ))
//))
{
echo "{$info['Que_ID']} <br />\n";
echo "<input type='hidden' name=\"Que_ID\" value=\"{$info['Que_ID']}\" /> ";
echo "{$info['Que_Question']} <br />\n";
echo "<input type=\"checkbox\" name=\"choice[$counter]\" value=\"{$info['Que_Choice1']}\" /> ";
echo "{$info['Que_Choice1']} <br />\n";
$counter++;
echo "<input type=\"checkbox\" name=\"choice[$counter]\" value=\"{$info['Que_Choice2']}\" /> ";
echo "{$info['Que_Choice2']} <br />\n";
$counter++;
echo "<input type=\"checkbox\" name=\"choice[$counter]\" value=\"{$info['Que_Choice3']}\" /> ";
echo "{$info['Que_Choice3']} <br />\n";
$counter++;
echo "<input type=\"checkbox\" name=\"choice[$counter]\" value=\"{$info['Que_Choice4']}\" /> ";
echo "{$info['Que_Choice4']} <br />\n";

$counter++;
}

?>
<input type="submit" value="submit"/>

</form>
</body>

</html>

</body>

</html>

SQL

CREATE TABLE IF NOT EXISTS `info` (
  `Que_ID` int(11) NOT NULL AUTO_INCREMENT,
  `Que_Question` varchar(255) NOT NULL,
  `Que_Choice1` varchar(255) NOT NULL,
  `Que_Choice2` varchar(255) NOT NULL,
  `Que_Choice3` varchar(255) NOT NULL,
  `Que_Choice4` varchar(255) NOT NULL,
  PRIMARY KEY (`Que_ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO `info` (`Que_ID`, `Que_Question`, `Que_Choice1`, `Que_Choice2`, `Que_Choice3`, `Que_Choice4`) VALUES
(1, 'What Color is the sun', 'red', 'green', 'blue', 'white'),
(2, 'Are IPhones cool', 'yes', 'no', 'maybe', 'who cares');

 

PHP

<HTML>
<BODY>
<?php
if($_POST){
echo "<pre>";
	print_r($_POST);
echo "</pre>";
}else{
$dbhost = 'localhost';
$dbuser = 'Your_Username_Here';
$dbpass = 'Your_Password_Here';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db('phpfreaks', $conn);
$query = 'SELECT * FROM info';
$result = mysql_query($query);
$counter = 1;
?>
<form action="<? echo $PHP_SELF; ?>" method="POST">
<?php 
while( $info = mysql_fetch_assoc($result))	{
	echo "{$info['Que_ID']} <br />\n";
	echo "<input type='hidden' name=\"Que_ID_{$info['Que_ID']}\" value=\"{$info['Que_ID']}\" /> ";
	echo "{$info['Que_Question']} <br />\n";
	echo "<input type=\"checkbox\" name=\"Que_ID_{$info['Que_ID']}[]\" value=\"{$info['Que_Choice1']}\" /> ";
	echo "{$info['Que_Choice1']} <br />\n";
	echo "<input type=\"checkbox\" name=\"Que_ID_{$info['Que_ID']}[]\" value=\"{$info['Que_Choice2']}\" /> ";
	echo "{$info['Que_Choice2']} <br />\n";
	echo "<input type=\"checkbox\" name=\"Que_ID_{$info['Que_ID']}[]\" value=\"{$info['Que_Choice3']}\" /> ";
	echo "{$info['Que_Choice3']} <br />\n";
	echo "<input type=\"checkbox\" name=\"Que_ID_{$info['Que_ID']}[]\" value=\"{$info['Que_Choice4']}\" /> ";
	echo "{$info['Que_Choice4']} <br />\n";
	$counter++;
}
?>
<input type="submit" value="submit"/>
</form>
<?php mysql_close($conn); } ?>
</BODY>
</HTML>

 

This is a simple example of how I think it should be working.

@xxreenaxx1. You got two options. Either show me what you got now and I can help you go through the code to find out why its doing what you say it is, or create a new table called info in a test database importing the SQL I provided, and create a new index.php page with the php code I provided and then you can see whats happening.

I have tried your way.

 

<HTML>
<BODY>
<?php
if($_POST){	
echo "<pre>";		
print_r($_POST);	
echo "</pre>";}
else{	
$dbhost = 'localhost';	
$dbuser = 'root';	


$dbpass = '';	
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');	
mysql_select_db('test', $conn);	
$query = "SELECT * FROM test";	
$result = mysql_query($query);	
$counter = 1;?>	
<form action="<? echo $PHP_SELF; ?>" method="POST">	
<?php 	
while( $info = mysql_fetch_assoc($result))	{		
echo "{$info['Que_ID']} <br />\n";		
echo "<input type='hidden' name=\"Que_ID_{$info['Que_ID']}\" value=\"{$info['Que_ID']}\" /> ";		
echo "{$info['Que_Question']} <br />\n";	
echo "<input type=\"checkbox\" name=\"Que_ID_{$info['Que_ID']}[]\" value=\"{$info['Que_Choice1']}\" /> ";		
echo "{$info['Que_Choice1']} <br />\n";	
echo "<input type=\"checkbox\" name=\"Que_ID_{$info['Que_ID']}[]\" value=\"{$info['Que_Choice2']}\" /> ";		
echo "{$info['Que_Choice2']} <br />\n";		
echo "<input type=\"checkbox\" name=\"Que_ID_{$info['Que_ID']}[]\" value=\"{$info['Que_Choice3']}\" /> ";	
echo "{$info['Que_Choice3']} <br />\n";	
echo "<input type=\"checkbox\" name=\"Que_ID_{$info['Que_ID']}[]\" value=\"{$info['Que_Choice4']}\" /> ";	
echo "{$info['Que_Choice4']} <br />\n";	
$counter++;	}	?>
<input type="submit" value="submit"/>	
</form><?php mysql_close($conn); } ?>
</BODY>
</HTML>

 

this is the message I am getting

Array

(

    [Que_ID] => 5

    [choice] => Array

        (

            [2] => Array

                (

                    [0] => on

                )

 

        )

 

    [submit] => submit

)

 

output of your last post is not from your form code

are you shure that edit right file

i insert some coments in your code

i'm shure you can understund it

i think that is beter way to choice separeted wit questin

while( $info = mysql_fetch_array( $sqll ))
//))
{
echo "{$info['Que_ID']} <br />\n"; // i hope that is PK from your table
echo "<input type='hidden' name=\"Que_ID\" value=\"{$info['Que_ID']}\" /> ";
// name from this field must be array
//it's mean that name=\"Que_ID[]\" add [] to name
echo "{$info['Que_Question']} <br />\n";
echo "<input type=\"checkbox\" name=\"choice[$counter]\" value=\"{$info['Que_Choice1']}\" /> ";
//transform name in 2 dimensinal array
//1st dimension is for which question is answer, and 2nd just for enable multliply answers
// name=\"choice[{$info['Que_ID']}][]\"
// if $info['Que_ID'] = 1 in $_POST['choice'][1] is array of all chcked ansvers for question with id=1
// $_POST['choice'][12] is array of all chcked ansvers for question with id=12 etc.
//warning! if noting checked for questinh x, $_POST['choice'][x] is not set
// if notin checked at all $_POST['choice'] is not set
echo "{$info['Que_Choice1']} <br />\n";
...

I am kind of confused.

 

So far I can print the choices but not the Question ID according to that.

 

while($submit = $_POST['submit']){
$questionid= $_POST['Que_ID'];
echo "Question ID: $questionid";

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

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

    echo "choice id: $question. value: $val";
  }
  

  }

 

For this code Question ID just get repeated by the last question. And its not meant to do that.

 

My form has been changed to

 

$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=\"Radio\" name=\"choice{$info['Que_ID']}.{$i} []\" />{$info['Que_Choice'.$i]}<br />\n";  
  $intnumber++;
}
}
?>

<input type="submit" value="submit" name="submit">
</form> 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.