Hi All: I am new to creating arrays and am trying to create a variable to hold a list of items and print it multiple times on a page. Below is the PHP that I've attempted and below that is the HTML which shows the same SELECT list multiple times on the page. It is only listing the first item in the SELECT list. Other tweaks have resulted in the SELECT list having the complete list of items from the database, but any other calls to this variable elsewhere on the page fails.
What can I do to get a variable to hold this SELECT list so that I can print it multiple times on the page?
<?php
$catresult = mysql_query("SELECT * FROM Classes WHERE FK_UserID=$_SESSION[user_id] ORDER BY ClassName");
$dataset = array();
while($row = mysql_fetch_array($catresult)) {
$dataset = '<option value="' . $row['ClassID'] . '">' . $row['ClassName'] . '</option>';
}
?>
<!-- HTML below -->
Paragraph 1 content...
<select name="FK_ClassID" /><option value="">Class</option><?php echo $dataset; ?></select>
Paragraph 2 content...
<select name="FK_ClassID" /><option value="">Class</option><?php echo $dataset; ?></select>
Paragraph 3 content...
<select name="FK_ClassID" /><option value="">Class</option><?php echo $dataset; ?></select>
Just to clarify what others have already pointed out:
What you are doing does not require an array. What you want is for $dataset
to contain one long string with all the options. So, instead of $dataset = array();
use $dataset = '';
.
In addition, the =
sign overwrites whatever was in your variable before that. You don't want that. You want to concatenate (add on) the new string on the old one. For that you'll use .=
.
So, to tie it all together:
<?php
$catresult = mysql_query("SELECT * FROM Classes WHERE FK_UserID=$_SESSION[user_id] ORDER BY ClassName");
$dataset = '';
while( $row = mysql_fetch_array($catresult) )
{
$dataset .= '<option value="' . $row['ClassID'] . '">' . $row['ClassName'] . '</option>';
}
?>
First, initialize $dataset
with empty string. Then in the while loop, use .= (instead of =) to append those <option>
s to $dataset
.
In your loop, you are reassigning the $dataset
variable rather than either appending to it or adding array elements (your code doesn't make it clear which you want to do). If you want to append it as a string, use $dataset .= ...
or if you'd like to keep it as an array use $dataset[] = ...
.
If you're wanting to go the string route, make sure you change $dataset = array()
to $dataset = '';