Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

for loop 1

Status
Not open for further replies.

kzn

MIS
Jan 28, 2005
209
GB
Hi
I am new to php mysql. Here is the problem I am having:

I run the below mysql select statement, it give the following results:
q column answer
what is your name? jon
what is your name? ken
what is your name? Rob
where do you live? UK
where do you live? US
where do you live? Ireland

I want my query to display one question with three possible answers, example.
what is your name? jon ken rob
where do you live? UK US Ireland

I am not sure if I should be using a for loop. I am new to this and finding it really hard.


Thanks in advance for you help.


$query = "select questions.question as q, answers.answer from questions,answers where questions.questionID = answers.questionID";

$result = mysql_query($query); // run the query

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

for($i=0;$i <=3;$i++) {
$i = $row['q'];
}

echo '<tr>
<td align="left">' . $i . ':</td>
<td align="left">'. $row['answer'] .'</td>
</tr>';

}
 
There are two ways to do what you are trying to do. Neither of them is going to use a for-loop, as you don't have anything to loop through.

The first method is to keep track of the current question and only start a new line of the table when there is a new question. The basic loop code might be something like:

Code:
$query = "select questions.question as q, answers.answer from questions,answers where questions.questionID = answers.questionID order by q, answer";
$result = mysql_query($query, $dbh);

print '<table border="1">
';

$current_question = '';
while ($row = mysql_fetch_assoc($result))
{
	if ($row['q'] != $current_question)
	{
		$current_question = $row['q'];
		
		print '	<tr><td>' . $current_question;
	}

	print '<td>' . $row['answer'];
}

Contrariwise, you could split up your query into two queries, one generated by the output of the other:

Code:
$query1 = "select questions.questionID, questions.question as q from questions";
$result1 = mysql_query($query1, $dbh);

print '<table border="1">
';

while ($row1 = mysql_fetch_assoc($result1))
{
	print '	<tr><td>' . $row1['q'];
	
	$query2 = "SELECT answer from answers where questionID = " . $row1['questionID'];
	
	$result2 = mysql_query($query2, $dbh);
	
	while ($row2 = mysql_fetch_assoc($result2))
	{
		print '<td>' . $row2['answer'];
	}
}



Want the best answers? Ask the best questions! TANSTAAFL!
 
sleipnir214
Thanks very much for your help, just what I wanted. I have read many books but have not put it into practice, finding it very hard.

Thanks again for your time on this.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top