I don't get all the data from mysql - PHP - php

I've been searching for this for while but didn't find anything related.
So my problem is that I do get all the data from mysql with while(). However, all the articles I am trying to get displays as only 1 article even though the content is different. Sorry, it's not easy to explain that but see pictures below:
My database:
How it is displayed:
my articlesFunction.php code:
// check if user is logged in to view the content:
if(!isset($_SESSION['loggedin']) && !isset($_SESSION['loggedinAdmin'])){
header("Location: login.php");
}else{
}
//
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//
my articles.php:
<?php
///////////////////////////////////////////////////////////////////////////////////////
// UNFINISHED //
///////////////////////////////////////////////////////////////////////////////////////
session_start();
require_once 'connect.php';
include 'articlesFunction.php';
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog posts</title>
<link rel="stylesheet" href="css/articles.css">
</head>
<body>
<div id="bannerDiv" style="background-image: url(images/banner.jpg); background-size: 100% 100%; height:150px;">
<h2 id="bannerTitle"><u><i>Articles about travel that everyone loves...</i></u></h2>
<p>Homepage</p>
<span id="BannerMenu"><?php echo 'logged in as: '.$_SESSION['username'].' ';?></span><button>Logout</button>
</div>
<div id="container">
<div id="articles">
<div id="Display Articles">
<h1><u>Our set of articles:</u>
</h1>
<div id="display">
<?php
echo $fullArticle;
?>
</div>
</div>
</div>
</div>
</body>
</html>
So, I hope you understand my issue now. First, in this example, when I put it alone in the div, I only get the oldest article and I get only 1. If I add a while to the div, It gives me the results in the picture above:
So, how can I display the articles (all of them) and each one to be different as they are in the database.

You are overwriting your variable on every iteration of the while loop.
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}
so as a simple example
$a = 0;
$b = 3;
while($a < $b){
$output = $a;
$a++;
}
echo $output;
This gives back 2 because $output is being over written every-time. There are two approaches to keeping all the values.
Option one, concatenate the variable
$a = 0;
$b = 3;
$output = '';
while($a < $b){
$output .= $a;
$a++;
}
echo $output;
Which will output 012. We have to define the variable before using it with the .=. With the .= it is trying to concatenate the value first so it must already exist.
Option two, store the values in an array
$a = 0;
$b = 3;
while($a < $b){
$output[] = $a;
$a++;
}
print_r($output);
This will output:
Array
(
[0] => 0
[1] => 1
[2] => 2
)
This way is a bit more work because when you want to access it later you have to re-iterate through it. However it can be better if you want to be able to access each data point separately.
foreach($output as $value) {
echo $value;
}
Also note if users are providing their usernames, article name, or description and you aren't filtering that this will open you to XSS injections.
https://en.wikipedia.org/wiki/Cross-site_scripting
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#A_Positive_XSS_Prevention_Model
Usage in your actual code would be:
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>

This should be your code, in order to avoid the errors you mentioned in the comments;
//init fullname variable
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//

Related

Very strange occurence mysql php blog

Ok so the problem I'm having is very strange. I have a blog website that displays a list of posts, and i made a system to select only 10 posts at a time. and yet on the second generated page 12 results are shown (the last 2 are duplicates)
//removed url because problem solved and i dont want to get sql injected
if you goto my project above and look at the second page of posts 12 entry's are shown with the last 2 being duplicates of the 3rd(and last) page...what is going on?! they should not be able to appear because the sql LIMIT function should restrict the displayed posts to 10.
here is the code for mainpage .php
<?php
session_start();
ob_start();
if ($_SERVER["REQUEST_METHOD"] == "POST"){//this works in my tests.
$low = 0;
$high = 10; //this loop/if method works in conjunction with the code at the bottom of this page
$e = 1;//starts at 1 because 1 itself is defined my default at the bottom of the page
while($_SESSION['i'] != $e){
$e++;
if (isset($_REQUEST["p$e"])){
$u = 1;
while($u != $e){
$u++;
$low = $low + 10;
$high = $high +10;
}
}
}}else{
$low = 0;
$high = 10;
}
?>
<!doctype html>
<!-- AUTHOR:JOSH FAIRBANKS -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home Page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<nav>
<ul>
<li><div id = "new">Create new post</div></li>
<li><div id = "veiw">Veiw posts</div></li>
</ul>
</nav>
<main>
<?php
$link = mysqli_connect( 'localhost', 'username', 'password' );
mysqli_select_db( $link, 'mydatabasename' );
$results = mysqli_query( $link, "SELECT LEFT(post, 575) as post FROM Users where verified = 1 ORDER BY `id` DESC LIMIT $low , $high" ); //this displayes all the posts that have been verified
while( $record = mysqli_fetch_assoc( $results ) ) {
$post = $record['post'];
$count = mysqli_affected_rows( $link );
//ORDER BY YEAR(Date) DESC, MONTH(Date) DESC, DAY(DATE) DESC
$post .= "</td></tr></table>";
print $post;
}
$vresults = mysqli_query( $link, "SELECT post FROM Users where verified = 1" );
while( $vrecord = mysqli_fetch_assoc( $vresults ) ) {
$vpost = $vrecord['post'];
$vcount = mysqli_affected_rows( $link );
$_SESSION['vcount'] = $vcount;
//
//these mirror variables arent seen and just are used to count the total amount of posts
//not just the ones on the page
}
mysqli_free_result( $results );
mysqli_close( $link );
?>
<form method = "post" action = "mainPage.php">
<table>
<tr><td>Page Number: </td><!--<td><input type = "submit" name = "p1" value = "1"></td>-->
<?php
$i = 0;
print "displaying low: $low high: $high";
for($j = 0; $j < $vcount; $j++) //modulus
{
if($j % 10 == 0)
{
$i++;
$_SESSION['i'] = $i;
print "<td><input type = 'submit' name ='"."p".$i. "' value = '$i'></td>";
}
}
?>
</tr>
</table>
</form>
</main>
</body>
</html>
I know this code is a bit of a mess :p but i swear it works except for this frustrating issue. any and all help appreciated.
I guess your problem at $high variable... Records per page always constant. But seems that you are increment in one place.
if ($_SERVER["REQUEST_METHOD"] == "POST"){//this works in my tests.
$low = 0;
$high = 10; //this loop/if method works in conjunction with the code at the bottom of this page
$e = 1;//starts at 1 because 1 itself is defined my default at the bottom of the page
while($_SESSION['i'] != $e){
$e++;
if (isset($_REQUEST["p$e"])){
$u = 1;
while($u != $e){
$u++;
$low = $low + 10;
$high = 10;
}
}
}}else{
$low = 0;
$high = 10;
}
?>

Incorporating extra loop into random selection?

I have the code below that is selecting a random set of questions from Wordpress.
<?php
$rows = get_field('step_by_step_test');
$row_count = count($rows);
$rand_rows = array();
$questions = get_field('select_number_of_questions');
for ($i = 0; $i < min($row_count, $questions); $i++) {
$r = rand(0, $row_count - 1);
while (array_search($r, $rand_rows) !== false) {
$r = rand(0, $row_count - 1);
}
$rand_rows[] = $r;
echo $rows[$r]['question'];
}
?>
I want to incorporate a bit of extra code (below), how can I make sure it's selecting the same random question?
<?php if(get_sub_field('answer_options')): ?>
<?php while(has_sub_field('answer_options')): ?>
<?php echo the_sub_field('answer'); ?>
<?php endwhile; ?>
<?php endif; ?>
Why dont you change your approach slightly?
<?php
$rows = get_field('step_by_step_test'); // Get the test
$question_count = get_field('select_number_of_questions'); // Get the number of questions
$rows = shuffle($rows); // Randomize your questions
$rows = array_slice($rows, $question_count); // Now set the array to only contain the number of questions you wanted
foreach ($rows as $row) {
echo $row['question']; // Show the question
if(get_sub_field('answer_options', $row['id'])) {
while(has_sub_field('answer_options', $row['id'])) {
echo the_sub_field('answer');
}
}
}
?>
I made the assumption that you can alter "get_sub_field" to include the ID of the question, so you can then include the ID in your "where" field of "answer_options". This will allow you to link the question.
I think that what you need is to set up the whole thing in a loop. query by custom field
Or you could store the ids of the questions you got above, an then, below, query for the answers for those specific posts.
Here's how I randomized my WordPress slider using the Advanced Custom Fields plugin + Royal Slider with a modified version of TheSwiftExchange's code above
<div id="full-width-slider" class="royalSlider heroSlider rsMinW">
<?php
/*
* Slider Repeater field shuffled
* http://stackoverflow.com/questions/12563116/incorporating-extra-loop-into-random-selection
*/
$rows = get_field('slider');
// For Debugging:
// echo "<pre>";
// var_dump($rows);
// echo "</pre>";
$quotes = get_field('slide_text'); // Get the number of images
shuffle($rows); // Randomize your slides
foreach ($rows as $row) {
$slideImageID = $row['slide_image'];
$slideImage = wp_get_attachment_image_src( $slideImageID, 'full' );
$slideText = $row['slide_text'];
?>
<div class="rsContent">
<div class="royalCaption">
<div class="royalCaptionInner">
<div class="infoBlock">
<?php if(!empty($slideText)) {
echo $slideText;
}; ?>
</div>
</div>
</div>
<img src="<?php echo $slideImage[0]; ?>" class="" />
</div><!-- /.rsContent -->
<?php } // end foreach ?>
</div><!-- /slider-wrap -->

Array doesn't appear to be holding data

I have a system where I rearrange navigational items.
It stores the new order in an array and then I use a for loop to go through the array and update the database.
<?php
$apageid = array();
$apagename = array();
$apageorder = array();
$q = "SELECT g.id, g.title, n.order FROM tbl_general g INNER JOIN tbl_navigation n ON n.pageid = g.id WHERE n.type = '$_SESSION[parent]' ORDER BY n.order";
$return = $database->query($q);
while($row=mysql_fetch_assoc($return)){
$apageid[] = $row['id'];
$apagename[] = $row['title'];
$apageorder[] = $row['order'];
}
$count = count($apageid);
$bpageid = array();
$bpageorder = array();
?>
<div class="form-holder">
<?php
//run through each page one at a time and update the order of the menu
mysql_data_seek( $return, 0 ); //reset the pointer to do the same query
$i = 0; //the count for saving the new configuration
while($row=mysql_fetch_assoc($return)){
$id = $row['id'];
$title = $row['title'];
$order = $row['order'];
?>
<div class="form-row">
<div class="form-label">
Page Name
</div>
<div class="form-field">
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
<?php
for($j=0; $j<$count; $j++){
if($apageid[$j] == $id) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageid[$j]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apagename[$j]; ?></option>
<?php
}
?>
</select>
<select class="select-small" name="<?php echo $bpageorder[$i]; ?>">
<?php
for($k=0; $k<$count; $k++){
if($apageorder[$k] == $order) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageorder[$k]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apageorder[$k]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<?php
$i++;
}
?>
This first chunk of code is the menu where you can reorder items.
Initially it loads up the current select and allows you to change the ordering.
function reorderChildren($pageid, $pageorder){
global $database;
$count = count($pageid);
//run through each page one at a time and update the order of the menu
for($i=0; $i<$count; $i++){
//set a few variables
$pid = $pageid[$i];
$porder = $pageorder[$i];
echo "pid = $pid porder = $porder";
$q = "UPDATE tbl_navigation SET order = '$porder' WHERE pageid = '$pid' AND type = '$_SESSION[parent]'";
$database->query($q);
}
return 0;
}
The information then ends up being passed here and the problem appears to be the for loop is never executed.
Can anyone see why this would be?
It's not the naming used, I've checked them.
Am I storing information in the arrays correctly?
Can I make it clear that it's $bpageid and $bpageorder that are the arrays carrying the information forward.
Thanks!
Was a simple fix!
The problem was that the select name needed to be just name="bpageid[]" rather than what I listed above. Silly!
You have just initilized $bpageid = array(); at top after first while loop.No value is assigned
after that you using
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
but no value is in $bpageid[$i] so name of this select box is blank.
It might be problem. check this and do as required.
you could try to construct a json from the options of the select element store it to a hidden field or send ajax request to php script for processing , order could be made from a "weight" value 1,2,3 etc.... sort it with php and loop to display

Using for loop to speed up PHP code typing

Hi everyone I've been extracting rows from a SQL table 1 by 1. I wrote this code two years ago and realise how hideously ineffective it is. I'd like to speed things up by typing up a simple for-loop to automate the coding.
$maxRows_dd1 = 10;
$pageNum_dd1 = 0;
if (isset($_GET['pageNum_dd1'])) {
$pageNum_dd1 = $_GET['pageNum_dd1'];
}
$startRow_dd1 = $pageNum_dd1 * $maxRows_dd1;
$maxRows_dd2 = 10;
$pageNum_dd2 = 1;
if (isset($_GET['pageNum_dd2'])) {
$pageNum_dd2 = $_GET['pageNum_dd2'];
}
$startRow_dd2 = $pageNum_dd2 * $maxRows_dd2;
$maxRows_dd3 = 10;
$pageNum_dd3 = 2;
if (isset($_GET['pageNum_dd3'])) {
$pageNum_dd3 = $_GET['pageNum_dd3'];
}
$startRow_dd3 = $pageNum_dd3 * $maxRows_dd3;
... dd4 to dd99 go in between!
$maxRows_dd100 = 10;
$pageNum_dd100 = 99;
if (isset($_GET['pageNum_dd99'])) {
$pageNum_dd32 = $_GET['pageNum_dd99'];
}
$startRow_dd99 = $pageNum_dd99 * $maxRows_dd99;
which corresponds to:
mysql_select_db($database_rent, $rent);
$query_dd1 = "SELECT * FROM rent";
$query_limit_dd1 = sprintf("%s LIMIT %d, %d", $query_dd1, $startRow_dd1, $maxRows_dd1);
$dd1 = mysql_query($query_limit_dd1, $rent) or die(mysql_error());
$row_dd1 = mysql_fetch_assoc($dd1);
if (isset($_GET['totalRows_dd1'])) {
$totalRows_dd1 = $_GET['totalRows_dd1'];
} else {
$all_dd1 = mysql_query($query_dd1);
$totalRows_dd1 = mysql_num_rows($all_dd1);
}
$totalPages_dd1 = ceil($totalRows_dd1/$maxRows_dd1)-1;
mysql_select_db($database_rent, $rent);
$query_dd2 = "SELECT * FROM rent";
$query_limit_dd2 = sprintf("%s LIMIT %d, %d", $query_dd2, $startRow_dd2, $maxRows_dd2);
$dd2 = mysql_query($query_limit_dd2, $rent) or die(mysql_error());
$row_dd2 = mysql_fetch_assoc($dd2);
if (isset($_GET['totalRows_dd2'])) {
$totalRows_dd2 = $_GET['totalRows_dd2'];
} else {
$all_dd2 = mysql_query($query_dd2);
$totalRows_dd2 = mysql_num_rows($all_dd2);
}
$totalPages_dd2 = ceil($totalRows_dd2/$maxRows_dd2)-1;
mysql_select_db($database_rent, $rent);
$query_dd3 = "SELECT * FROM rent";
$query_limit_dd3 = sprintf("%s LIMIT %d, %d", $query_dd3, $startRow_dd3, $maxRows_dd3);
$dd3 = mysql_query($query_limit_dd3, $rent) or die(mysql_error());
$row_dd3 = mysql_fetch_assoc($dd3);
if (isset($_GET['totalRows_dd3'])) {
$totalRows_dd3 = $_GET['totalRows_dd3'];
} else {
$all_dd3 = mysql_query($query_dd3);
$totalRows_dd3 = mysql_num_rows($all_dd3);
}
$totalPages_dd3 = ceil($totalRows_dd3/$maxRows_dd3)-1;
... all the way to dd100!!!
How would I use a for loop to speed typing up all this code for each block of code from dd1 to dd100?
Read about arrays and for() loops.
This is a much more efficient code to do exactly what you do above:
<?php
// You only need to do these once as they are the same throughout
mysql_select_db($database_rent, $rent);
$maxRows = 10;
// This code gets the total number of rows in the database
$totalRowsAll = mysql_fetch_assoc(mysql_query("SELECT count(*) AS total FROM rent", $rent));
$totalRowsAll = (int) $totalRowsAll['total'];
?>
<div class="tab_container">
<div id="tab1" class="tab_content">
<table width="100%" border="0" cellspacing="5" cellpadding="5" id="1">
<?php
for ($i = 0; $i < 100; $i++) {
// Calcluate value for this iteration and query database
$pageNum = (isset($_GET['pageNum_dd'.($i + 1)])) ? (int) $_GET['pageNum_dd'.($i + 1)] : $i;
$startRow = $pageNum * $maxRows;
$query = "SELECT * FROM rent LIMIT $startRow, $maxRows";
$result = mysql_query($query, $rent) or die(mysql_error($rent));
$totalRows = (isset($_GET['totalRows_dd1'])) ? (int) $_GET['totalRows_dd1'] : $totalRowsAll;
${'totalPages_dd'.($i + 1)} = ceil($totalRows / $maxRows) - 1;
// Now print this row
?>
<tr height="100px" align="center">
<?php
while ($row = mysql_fetch_assoc($query)) {
?>
<td style="background-color: <?php echo $row['colour']; ?>;" onclick="window.location='pay.php?id=<?php echo $row['dNo']; ?>&user=<?php echo $username; ?>'" onmouseover="this.style.cursor='pointer'">
<form action="pay.php?id=<?php echo $row['dNo']; ?>&user=<?php echo $username; ?>" method="post">
<input type="hidden" id="<?php echo $row['dNo']; ?>">
<input type="hidden" value="<?php echo $username; ?>">
<button type="submit" class="link" id="t<?php echo $row['dNo']; ?>">
<span><?php echo $row['dNo']; ?></span>
</button>
</form>
</td>
<?php
} // End while
?>
</tr>
<?php
} // End for
?>
</table>
</div>
</div>
...however:
I'm fairly sure this could be summed up in a single query to get all the results you need, which would be much more efficient and drastically reduce database load. But because of the $_GET['pageNum_dd*'] and $_GET['totalPages_dd*'] variables which are used on a per row basis, I am not 100% sure about this, and I can't work out how this would be done without knowing more about what is produced. You need to examine whether or not these parameters that can be passed are actually necessary/useful. As it is, they may be cause rows of a varying length, with an unequal number of cells per row - which is probably not what you want.
The same also goes for the variables $totalPages_dd*, which are assigned below but never used anywhere. They may not be useful, and assigning them may be pointless.

Reduce number of MySQL Queries and Output Data in Correct Order

My main issue is the number of times I query the database (see below). Also, I would like to check that the current product (optionsToProducts.productID) has options for the current optionName before outputting the select statement! See the final image below to see the blank select box...
I have 8 tables in total, but the 3 that matter are:
optionNames
http://www.grabb.co.uk/stack/001.png
productOptions
http://www.grabb.co.uk/stack/002.png
optionsToProducts
http://www.grabb.co.uk/stack/003.png
<?php
$i=0;
$optionsquery = "SELECT * FROM optionNames WHERE categoryID = ".$categoryID."";
$optionsresult= mysql_query($optionsquery) or die(mysql_error());
while ($optionnames = mysql_fetch_array($optionsresult)) {
$i++;
$optionname = $optionnames["optionName"];
$optionID = $optionnames["optionNamesID"];
//echo $optionname."<br />";
?>
<label for="option<?php echo $i; ?>"><?php echo $optionname; ?></label>
<select name="option<?php echo $i; ?>" id="<?php echo $i; ?>">
<?php
//$optionvalues = "SELECT * FROM (optionsToProducts,productOptions) WHERE optionsToProducts.productID = ".$productID." AND productOptions.optionNamesID = ".$optionID."";
//echo $optionvalues."<br /><br />";
$optionvalues = "SELECT * FROM optionsToProducts WHERE productID = ".$productID."";
$valuesresult= mysql_query($optionvalues) or die(mysql_error());
while ($optionvals = mysql_fetch_array($valuesresult)) {
$valueName = $optionvals["optionValue"];
$valueID = $optionvals["productOptionsID"];
//echo $valueName."<br />";
$optionfinal = "SELECT * FROM productOptions WHERE productOptionsID = ".$valueID." AND optionNamesID = ".$optionID."";
$finalresult= mysql_query($optionfinal) or die(mysql_error());
while ($optionlast = mysql_fetch_array($finalresult)) {
$optionValueName = $optionlast["optionValue"];
$optionValueID = $optionlast["productOptionsID"];
$num_rows = mysql_num_rows($finalresult);
?>
<option value="<?php echo $optionValueID; ?>"><?php echo $optionValueName; ?></option>
<?php
}
}
echo "</select>";
}
?>
final Output:
http://www.grabb.co.uk/stack/004.png
As always, your help is appreciated. Thank you.
Since you tagged this question with the join tag, you probably know you need to write a join query to get what you need.
<?php
$i=0;
$query = "SELECT options.optionName, options.optionNamesID, po.optionValue, po.productOptionsID
FROM optionNames AS options
INNER JOIN productOptions AS po ON po.optionNamesID=options.optionNamesID
INNER JOIN optionsToProducts AS otp ON otp.productOptionsID=po.productOptionsID
WHERE otp.productID=" . (int) $productID
. " AND options.categoryID=" . (int) $categoryID;
$result = mysql_query($query);
if($result) {
$rows = array();
while($row = mysql_fetch_assoc($result) ) {
$rows[] = $row;
}
$i = 0;
$optionId = null;
foreach($rows as $row) {
if($optionId != $row['optionNamesID']) {
$optionId = $row['optionNamesID'];
?>
<label for="option<?php echo $optionId; ?>"><?php echo $row['optionName']; ?></label>
<select name="option<?php echo $optionId; ?>" id="<?php echo $optionId; ?>">
<?php } ?>
<option value="<?php echo $row['productOptionsID']; ?>"><?php echo $row['optionValue']; ?></option>
<?php
//Close select element when the optionNamesID changes or on the last row
if( (isset($rows[$i + 1]) && $rows[$i + 1]['optionNamesID'] != $optionId) ||
!isset($rows[$i + 1]) ) { ?>
</select>
<?php }
$i++;
}
} else {
//Debug query, remove in production
echo mysql_error();
}
?>
I also made some small changes - I use the optionNamesID in the select and label tag names - I don't know how you knew previously which select belonged to which option.
I also assumed that categoryID and productID came from somewhere, since it's not specified in the code.
Pushing all the rows to an array at the beginning is optional, but it makes the code a bit more organized (since you can check ahead in the array to see where to close the select tags).
NOTICE - this code is untested so there could some minor typos. Please make the needed corrections if necessary.

Categories