Reused while loop only working for one selection box - php

I need to generate a list of teams from the cups selection box at the top of my page, this code allows me to run a while loop to generate the correct results for the first selection box, however, when i replicate the code in the second it shows no results?
<form class="seed-form">
<select name="team" required>
<option value='Holder' disabled selected>Select Team</option> <!--Placeholder for Select-->
<?php
while ($team = mysqli_fetch_assoc($show_teams)) { ?>
<option value="<?php echo $team["team_id"]; ?>"><?php echo $team["team_name"]; ?></option>
<?php } ?> <!--FILLS SELECT BOX WITH TEAMS FROM THAT CUP-->
</select>
<select name="team" required>
<option value='Holder' disabled selected>Select Team</option> <!--Placeholder for Select-->
<?php
while ($team = mysqli_fetch_assoc($show_teams)) { ?>
<option value="<?php echo $team["team_id"]; ?>"><?php echo $team["team_name"]; ?></option>
<?php } ?> <!--FILLS SELECT BOX WITH TEAMS FROM THAT CUP-->
</select>
<input type="submit" name="submit" value="Generate" class="submit">
<?php
if (isset($_POST['submit'])) { //checking if submit button was clicked
include_once 'action/dbcon.php';
$cname = $_POST['cupname'];
if (empty($cname)) {
header("Location: tables.php?field=empty"); //return them if fields are empty
exit();
} else {
$sql = "SELECT * FROM teams WHERE cup_name='$cname'";
$show_teams = mysqli_query($conn, $sql);
$numberCheck = mysqli_num_rows($show_teams);
if ($numberCheck < 8) {
header("Location: tables.php?tables=1"); //Take to cup page if there arent enough teams in the cup
}
}
}
?>

The problem is that fetch_assoc() returns the next row in the resultset, unless there are no more left (in which case it returns NULL - see docs).
Your first while loop runs until there are no more results. Therefore when you start the second while loop, there are still...you guessed it: no more results. You already used them up. Therefore the first call to fetch_assoc() in the second loop returns NULL immediately, and so the loop condition is never met, and the loop never executes.
There are two different ways to solve this:
1) Reset the result pointer to the start of the resultset. Somewhere between the two loops, write
mysqli_data_seek($show_teams, 0);
See docs for more info.
2) Read all the data into a PHP array, which you can then loop through as many times as you like using foreach:
<?php
$teams = array();
while ($team = mysqli_fetch_assoc($show_teams)) {
$teams[] = $team;
}
?>
<form class="seed-form">
<select name="team" required>
<option value='Holder' disabled selected>Select Team</option> <!--Placeholder for Select-->
<?php
foreach ($teams as $team) { ?>
<option value="<?php echo $team["team_id"]; ?>"><?php echo $team["team_name"]; ?></option>
<?php } ?><!--FILLS SELECT BOX WITH TEAMS FROM THAT CUP-->
</select>
<select name="team" required>
<option value='Holder' disabled selected>Select Team</option> <!--Placeholder for Select-->
<?php
foreach ($teams as $team) { ?>
<option value="<?php echo $team["team_id"]; ?>"><?php echo $team["team_name"]; ?></option>
<?php } ?> <!--FILLS SELECT BOX WITH TEAMS FROM THAT CUP-->
</select>

Related

Dropdownlist validation not working

I've try several times for dropdownlist validation,
my codes are in PHP and HTML, the the validation part is not working though and i've refer some of the solutions in stackoverflow which has similar case like mine.
Declare variable
$call_department = $db->escape((int)$_POST['call_department']); //where i declare this variable
HTML files
<tr><td>Department</td><td><select name='call_department'>
<option></option>
<?php $call_dept = $db->get_results("select type_id,type_name from site_types where type=1 order by type_name;");
foreach ($call_dept as $dept )
{?>
<option value='<?php echo $dept->type_id;?>'><?php echo $dept->type_name; required?></option>
<?php } ?>
</select></td></tr>
Validation part:
<?php
if(isset($_REQUEST['call_department']) && $_REQUEST['call_department'] == '0') {
echo 'Please select a department.';
}
?>
1) Set first option value="0" like this
<option value="0">select</option>
2) Required attribute should be set to select tag not to option tag <select name='call_department' required>
<select name='call_department' required>
<option value="0">select</option>
<?php $call_dept = $db->get_results("select type_id,type_name from site_types where type=1 order by type_name;");
foreach ($call_dept as $dept )
{
?>
<option value='<?php echo $dept->type_id;?>'><?php echo $dept->type_name; ?></option>
<?php } ?>
</select>

How to display same records in multiple drop down form database using PHP?

I have two drops down and I am able to display the records in one dropdown from a database. I am getting the second drop down list bank.I have to display same records in my second drop down but it is not displaying. If I delete first drop down then records are displaying in second drop down.I haven't change any think just copy paste the code.Would you help me in this?
<?php
$sql_emails="SELECT * FROM request";
$result_emails = $conn->query($sql_emails);
//first drop down
?>
<select class="selectpicker" name="first" data-live-search="true">
<option style="color:#bbb;" value="" disabled selected>Select emails</option>
<?php while($row = mysqli_fetch_array($result_emails)) { ?>
<option value="<?php echo $row['Email'];?>"><?php echo $row['Email'];?></option>
<?php } ?>
</select>
<?php mysqli_data_seek( $result_emails, 0 ); ?>
<select class="selectpicker" name="second" data-live-search="true" id="learner-emails">
<option style="color:#bbb;" value="" disabled selected>Select emails</option>
<?php while($row = mysqli_fetch_array($result_emails)){ ?>
<option value="<?php echo $row['Email'];?>"><?php echo $row['Email'];?></option>
<?php } ?>
</select>
mysqli_data_seek( $result_emails, 0 ); use this before second dropdown
Put the rows into an array at the beginning of your script.
$rows = [];
while($row = mysqli_fetch_array($result_emails))
$rows[] = $row;
Then, on the html sections, loop over the array. You can loop over it as many times as you want. You can't do that with the query results.
<?php foreach($rows as $row):;?>
<option value="<?php echo $row['Email'];?>"><?php echo $row['Email'];?></option>
<?php endfor;?>
mysqli_fetch_array() moves the pointer forward each time you call it. You need mysqli_data_seek() to set the pointer back to the start and then call mysqli_fetch_array() again.

Html Select Box Get value from mysql

Hi I have a stored value in mysql from a select box. When i call a edit page I would like the select box to populate with the value i have stored in mysql
$taskCompany = $mysqli->real_escape_string($_POST['taskCompany']); This returns 1
<select id="taskCompany" required name="taskCompany" class="form-control">
<option value="" disabled selected>Select a Company</option>
<option value="1">building</option>
<option value="2">maintenace</option>
</select></div>
I would like the select box to show the correct option when loading the edit page. I do not store any select option in the database values or text just the value that is select when job was created.
Thanks Jon
I'd I have understood correctly, you have he value/values in your MySQL database and you want them to be shown in your drop down list:
You could do it like:
<option value = "1" <?php if($taskCompany == 1) echo "select='selected'";?>>building</option>
Or if you have the names coming from the database too.
<select id="taskCompany" required name="taskCompany" class="form-control">
<option>SELECT</option>
<?php
$res = musql_query("SELECT * FROM yourtablename");
while($row = mysql_fetch_array($res))
{
$taskCompany = $row['taskCompany'];
$co_name = $row['taskCompanyName'];
?>
<option value = "<?php echo $taskCompany; ?>" ><?php echo co_name; ?></option>
<?php } ?>
Here I have used $co_name to be displayed as a name assuming that you have building, maintenance etc stored in your database.
This is for the time being, as I wanted to demonstrate but Please
consider mysqli/PDO as mysql_* is deprecated.
<?php $taskCompany = $mysqli->real_escape_string($_POST['taskCompany']); ?>
<select id="taskCompany" required name="taskCompany" class="form-control">
<option value="" disabled selected>Select a Company</option>
<option value="1" <?php if($taskCompany == 1) echo "selected='selected'"; ?>>building</option>
<option value="2" <?php if($taskCompany == 2) echo "selected='selected'"; ?>>maintenace</option>
</select></div>
You can do this
<?php foreach($taskCompany as $row){ ?>
<option value="unique id for select options">name for select options</option>
<?php } ?>

PHP & HTML : how to create dynamic drop down list

I have a little problem.
I'm searching the internet now for quite some time to find a proper solution but I was not successful so far.
This is what I want :
First, I choose Category
Then, in second selection contain all the store result from category selection.
this is my first drop down list which is contain Category :
<select name="category" class="form-control" id="select1">
<option value="-1"> - Choose One -</option>
<?php
$StoreCategoriesAPIAccessor = new StoreCategoriesAPIService(GuzzleClient::getClient());
$stores = $StoreCategoriesAPIAccessor->getStoreCategories();
foreach ($stores as $store):
?>
<option value="<?php echo $store->getStoreCategoryId(); ?>"><?php echo $store->getCategory(); ?></option>
<?php endforeach; ?>
</select>
this is my second drop down list :
<select name="category" class="form-control" id="select2">
<option value="-1"> - Choose One -</option>
<?php
$StoreAPIAccessor = new StoreAPIService(GuzzleClient::getClient());
$stores = $StoreAPIAccessor->getStores();
foreach ($stores as $store):
?>
<option value="<?php echo $store->getStoreId(); ?>"><?php echo $store->getStoreName(); ?></option>
<?php endforeach; ?>
</select>
Anyone know how to implement dynamic drop down list for this case ?
Well first of all I'd like to ask that you separate business logic from view logic as much as possible, so I will do that in this answer.
Secondly, the 2nd dropdown box logic that you have does not contain anything that would retrieve stores for a given category, I will therefore make some assumptions and you can adjust based on that.
<?php
$StoreCategoriesAPIAccessor = new StoreCategoriesAPIService(GuzzleClient::getClient());
$categories = $StoreCategoriesAPIAccessor->getStoreCategories();
if (!empty($_GET['category'])) {
$category_id = $_GET['category'];
$StoreAPIAccessor = new StoreAPIService(GuzzleClient::getClient());
$stores = $StoreAPIAccessor->getStores($category_id); // Assumption, the call to getStores() accepts category_id as a parameter
} else { // Optional as you don't need to declare variables in PHP, but its better practice to do so
$category_id = null;
$stores = array();
}
?>
<select id="select_category" name="category" class="form-control" onchange="window.location='?category=' + this.value">
<option value="">- Choose One -</option>
<?php foreach ($categories as $category): ?>
<option value="<?php echo $category->getStoreCategoryId() ?>"><?php echo $category->getCategory() ?></option>
<?php endforeach ?>
</select>
<select id="select_store" name="store" class="form-control"<?php echo $category_id == null ? " disabled='disabled'" : "">
<option value="">- Choose One -</option>
<?php foreach ($stores as $store): ?>
<option value="<?php echo $store->getStoreId() ?>"><?php echo $store->getStoreName() ?></option>
<?php endforeach ?>
</select>

Get array for dropdown from foreach parent

I have 2 arrays (one inside the other), where one goes through a list of questions - and the other contains the list of options for the dropdown menu.
<?php foreach ($modelSettings as $name=>$item):?>
<select name="<?php echo 'model'.($i+1).'['.$name.']' ?>" >
<?php foreach($item['options'] as $value):?>
<option value="<?php echo $value?>"><?php echo ucfirst($value);?></option>
<?php endforeach;?>
</select>
<input type="hidden" name="<?php echo 'model'.($i+1).'[id]'?>" value="0"/>
<?php endforeach;?>
The result looks like this
<select name="model4[car]">
<option value="bmw">BMW</option>
<option value="toyota">Toyota</option>
<option value="volvo">Volvo</option>
</select>
<select name="model4[color]">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="white">White</option>
</select>
What I'm trying to do is to eliminate the first foreach so that I will write up every <select> manually, but have the list in the dropdown retrieved via an array.
I've been trying various things, among them this:
<select name="model4[car]" >
<?php foreach ($modelSettings as $name=>$item):?>
<?php foreach($name[0] as $value):?>
<option value="<?php echo $value?>"><?php echo ucfirst($value);?></option>
<?php endforeach;?>
<?php endforeach;?>
</select>
<input type="hidden" name="<?php echo 'model'.($i+1).'[id]'?>" value="0"/>
etc....
But I have been unsuccessful.
This is how the arrays are created in the backend.
public function getOptions()
{
$modelLabels = array('car' => __('Age'),
'color'=> __('Color'),
'fuel_type'=> __('Fuel Type'),
'transmission'=> __('Transmission'));
$tmpModelSettings = $this->list_columns();
unset($tmpModelSettings['id'], $tmpModelSettings['name']);
$modelSettings = array();
foreach($tmpModelSettings as $key=>$value)
{
$modelSettings[$key]['options'] = $value['options'];
$modelSettings[$key]['label'] = $modelLabels[$key];
}
return $modelSettings;
}
Sorry, I am new to this - and the PHP documentation did not help me to sufficiently understand code this complex (for me anyway :) )
Your attempt doesn't make much sense (why are you trying to iterate over a key reference?) You should access the particular array element within the $modelSettings array using the key reference. Then you can access the options element in that array subsequently and foreach over them.
<select name="model4[car]" >
<?php foreach($modelSettings['car']['options'] as $value):?>
<option value="<?php echo $value?>"><?php echo ucfirst($value);?></option>
<?php endforeach;?>
</select>
<input type="hidden" name="<?php echo 'model'.($i+1).'[id]'?>" value="0"/>

Categories