PHP Menu Select Option values - php

I have a form and a drop down menu for users to select Industy Job Sectors as part of their search, e.g. Accountancy, Construction, Engineering etc.
I've searched this forum for solutions regarding how to remember menu select option values AFTER submit and I'm grateful to have implemented a modified version from the solution I found here:
Simpliest way to remember DropDown selection?
//For example
if(is_post_request()) {
$jobsector['jobsector_id'] = $_POST['jobsector_id'] ?? '';
} else {
$jobsector['jobsector_id'] = '';
}
<div class="form-group">
<label for="jobsector">Job Sector:</label>
<select class="custom-select" name="jobsector_id" id="jobsector_id">
<option value="">Select Sector</option>
<?php
$query = "SELECT jobsectors.id, jobsectors.jobsector_name FROM jobsectors";
$results = mysqli_query($db, $query);
$_SESSION['jobsector_id'] = $jobsector['jobsector_id'];
$_POST['jobsector_id'] = $_SESSION['jobsector_id'];
//loop
foreach ($results as $jobsector): ?>
<option value="<?php echo h($jobsector['jobsector_name']); ?>"
<?php if ($jobsector['jobsector_name'] == $_POST['jobsector_id']){echo " selected";}?>>
<?= $jobsector['jobsector_name']; ?>
</option>
<?php endforeach;
unset ($_SESSION['jobsector_id']); ?>
</select>
</div>
However, I've run in to a problem where the menu select option values that I have, BEFORE the form is submitted, now show a notice/error:
Notice: Undefined index: jobsector_id
Here's a screen grab:
screenshot of undefined index notice
I realise that this will be because the POST value for 'jobsector_id' has not yet been submitted with the form, so my question is how do I get the menu select options to show in the drop down without this error, BEFORE the form is submitted?

I've added a session to store the value of 'jobsector_id' and then made $_POST['jobsector_id'] = $_SESSION['jobsector_id'] and finally unset the session. It all seems to work fine now. Thank you for your suggestions guys!

Related

Use mysql query result in more than one place in code

I'm building a system that tracks contact lenses. I'm storing the contact lens info in a database as sometimes prices/availabilities change and i access this info from multiple points in the program. I'm trying to interface with this list using a dropdown by doing "SELECT * FROM contacts" as a query. my code looks like this :
$contact_list = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
Then I echo that list out in a while loop using PHP to populate the options in the dropdown.
My question is this: I have these dropdowns for each eye on the same form. So it's "Brand Right Eye"....other miscellaneous info about the right eye....then "Brand Left Eye". But ONLY the right eye is populating with the brand info because it appears first in the code. What i'm having to do is copy/paste the exact same query and do
$contact_list2 = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
then later if I need the dropdown again, I need to do $contact_list3..and so on. Why can i not generate a drop down using the same variable? Why does it stop responding to calling the variable after the first execution of it and is there any work around that I can implement that would allow me to not have to copy/paste the same query with a different variable association each time?
just for refernce, my php while code is this:
<select class="form-control" name = "brandOS">
<option value="0">Please Select</option>
<?php
while($row = mysqli_fetch_array($contact_list))
{
?>
<option value = "<?php echo($row['brand'])?>" name = "brandOS">
<?php echo($row['brand']) ?>
</option>
<?php
}
?>
</select>
I have this loop copy/pasted for right eye and left eye. But it only works on which ever drop down appears first in the code.
A possible solution will be more efficient in term of performance could be :
<?php
$left_eye = '<option value="0">Please Select</option>';
$rigth_eye = '<option value="0">Please Select</option>';
while($row = mysqli_fetch_array($contact_list))
{
//logic for left eye
$left_eye .= <<<HTML
<option value ="{$row['brand']}" name = "brandOS">
{$row['brand']}
</option>
HTML;
//logic for rigth eye
$rigth_eye .= <<<HTML
<option value ="{$row['brand']}" name = "brandOS">
{$row['brand']}
</option>
HTML;
}
?>
<select class="form-control" name = "brandOS">
<?php echo $left_eye ; ?>
</select>
<select class="form-control" name = "brandOS">
<?php echo $rigth_eye ; ?>
</select>
With this solution you get your result in the same while loop. If the left and right select are the same you can use the same variable.
Store the brands in an array, then you can just loop through the array.
<?php
$contact_list = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
$brands = array();
while($row = mysqli_fetch_array($contact_list))
{
array_push($brands, $row['brand']);
}
?>
<select class="form-control" name = "brandOS">
<option value="0">Please Select</option>
<?php
foreach($brands as $brand){
?>
<option value = "<?php echo($brand[0])?>" name = "brandOS">
<?php echo($brand[0]) ?>
</option>
<?php
}
?>
</select>
You can use a PHP array, like the SESSION one, to store values and use them across your site. Be sure you call "session_start()" method on each page you use that array, though.
//Initialize sessions
session_start();
...
//Right after getting result from query
$_SESSION['contact_list'] = $contact_list;
To use it, just be sure to call the method I told you above, and call the variable with the same syntax:
<?php
while($row = mysqli_fetch_array($_SESSION['contact_list'])) { ?>
Hope this helps.

Saving a option field from a dynamic MySQL populated selectbox into another MySQL Table

I want to insert a option from a dynamic populated MySQL select box, into another table with other form variables. Please excuses all the newbie errors.
This is the area of my form where the select box appears:
<select class="form-control3" name="Select_Name" id="Select_Name">
<?php include('../../controllers/controller1.php') ?>
</select>
This is where it is declared in PHP:
$Select_Item1 = $_POST['Select_Item1'];
$Select_Item2 = $_POST['Select_Item2'];
$Select_Item3 = $_POST['Select_Item3'];
$Select_Item4 = $_POST['Select_Item4'];
$Select_Name = $_POST['Select_Name'];
$insert_movie = mysqli_query($con, "INSERT INTO ".$tbl_name." (Select_Item1, Select_Item2, Select_Item3, Select_Item4, Select_Name) VALUES ('". $Select_Item1."','". $Select_Item2."','". $Select_Item3."','". $Select_Item4."','".$Select_Name."')");
But when I submit the form, everything submits except the $_POST['Select_Name'];
Any help will be greatly valued. Thank you.
can you echo $_POST['Select_Name'] and see what is its value? Maybe you are not doing it right in the <?php include('../../controllers/controller1.php') ?>
Can I see what are you doing on you controller?
Also why dont you pass data from controller like a variable and do a foreach between the select command?
//codeigniter syntax
<select class="form-control3" name="Select_Name" id="Select_Name">
<?php foreach($var as $key):?>
<option value="<?=$key?>"><?=$key?></option>//sth like this
<? endforeach ?>
</select>

Posted multiselect box selection to database only adding the first selected item

i am using the following multiselect box to take input from users, this then gets posted to my php form which adds it to the database, the problem is, all I am getting added is the first selection, if the user selects more than one field I still only get the first field.
If the user selects lets say internet, drawing,maths I want that to be put into the database, at the moment all that is inserted is internet, or whatever is the first thing selected in the list.
My form looks like this >>
<form action="../files/addtodb.php" method="post" style="width:800px;">
<select name="whatisdeviceusedfor[]" size="1" multiple="multiple" id="whatisdeviceusedfor[]">
<option value="games">Games</option>
<option value="takingphotos">Taking Photos</option>
<option value="maths">Maths</option>
<option value="reading">Reading</option>
<option value="drawing">Drawing</option>
<option value="internet">Internet</option>
<option value="other">Other (enter more info below)</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
The php side looks like this >>
<?php
// Implode what is device used for
$usedfor = $_POST['whatisdeviceusedfor'];
$arr = array($usedfor);
$whatisdeviceusedfor = implode(" ",$arr);
// Insert posted data into database
mysql_query("INSERT INTO itsnb_year5questionaire (whatisdeviceusedfor) VALUES '$whatisdeviceusedfor'") or die(mysql_error());
?>
you are already getting array by select so you dont need to use $arr = array($usedfor);this again
just try
$usedfor = $_POST['whatisdeviceusedfor'];
$whatisdeviceusedfor = implode(" ",$usedfor);
or
$usedfor = $_POST['whatisdeviceusedfor'];
$strings ='';
foreach ($usedfor as $item){
$strings .=' '. $item;
}
echo $strings;
and
<select name="whatisdeviceusedfor[]" size="5" multiple="multiple" id="whatisdeviceusedfor[]">
^^
||change to option you want to select
i have changed size="5" so it will select now 5 at a time ...you have only 1 so it will let only 1 select at a time
result
warning
your code is vulnerable to SQL injection also use of mysql_* function are deprecated use either PDO or MySQLi
If you have selected mutliple items via a SELECT or via CHECKBOXES, the form will return an array-like data structure. You will always need to loop over that data and store each item individually into the database or concatenate the values to a string before inserting.
first change size = "5" to see good the list
then try to make like that (its second option if you like it)
if ($_POST) {
// post data
$games = $_POST["games"];
$takingphotos = $_POST["takingphotos"];
.
...
// secure data
$games = uc($games);
$boats = uc($takingphotos);
.
...
}
// insert data into database
$query = "INSERT INTO itsnb_year5questionaire (games, takingphotos,....)
VALUES('$games','$takingphotos',......)";
mysql_query($query) or die(mysql_error());
echo 'Thanks for your select!';
Because $usedfor is contain the array you can directly use it in foreach to save the each value in the value.Try this it may help you:
<?php
$usedfor = $_POST['whatisdeviceusedfor'];
foreach($usedfor as $arr){
mysql_query('INSERT INTO itsnb_year5questionaire(whatisdeviceusedfor) VALUES("'.$arr.'"') or die(mysql_error());
}

an option already selected on page load in drop down list and also changeble [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP - PRE-select drop down option
I have a situation in my php project where a user can edit his account.
In editing, there is a city field which is a drop down list of cities.
I want to already select one city which is in profile before editing(the one which user enter at the time of registration).
Also he is able to change his city by choosing fron drop down list.
Html code:
<div class="search_bar1_txt">State:</div>
<div class="search_bar1">
<select class="styled" name="state_trainer">
<option>-select-</option>
<option>washington</option>
<option>perth</option>
<option>delhi</option>
<option>london</option>
</select></div>
</div>
on editing I am using this code to fetch current data(city) of user:
<?php
if(isset($_GET['userid']))
{
$sql = "select city from `wp_pelleresuser` where userId =".$_GET['userid'];
$result = mysql_query($sql);
$value = mysql_fetch_assoc($result);
}?>
please tell me how can I get already selected one option which is fetch from database.
And also it is changeable.
<div class="search_bar1_txt">State:</div>
<div class="search_bar1">
<select class="styled" name="state_trainer">
<option <?if($value['city']=='-select-') echo "selected";?>>-select-</option>
<option <?if($value['city']=='washington') echo "selected";?>>washington</option>
<option <?if($value['city']=='perth') echo "selected";?>>perth</option>
<option <?if($value['city']=='delhi') echo "selected";?>>delhi</option>
<option <?if($value['city']=='london') echo "selected";?>>london</option>
</select>
</div>
</div>
You can do it in a number of ways, the simplest (and probably least elegant) is to do something like this:
<select class="styled" name="state_trainer">
<?php
$myCity='london'; // assumed to be data from database...
echo '<option'.($myCity=='-select-') ? ' selected ' : ' ' .'-select-</option>';
echo '<option'.($myCity=='washington') ? ' selected ' : ' ' .'washington</option>';
?>
This is of course horrid.
I would rather suggest that you check the data as you are pulling your information out of the database and putting your initial dropdown list together.
If you are making an array of data to create the drop down list (for example) check it right there and then. If the city matches what you want, do it inside your loop right off the bat.
$usersCity="london";
$myCityList=array();
while( ... ) // Database loop that is pulling the data from the database.
{
$selected='';
if($userCity==$row['city'])
{
$selected=' selected ';
}
$myCityList[]='<option'.$selected.'>'.$row['city'].'</option>';
}
Then to display the drop down list, you can simply do this:
$cityCount=count($myCityList);
for($i=0;$i<$cityCount;$i++)
{
echo $myCityList[$i].'\n';
}
The users city will already be selected.
I'm not sure if it is clear way but you can put code inside every option cell like this:
<option <?php if($value['city'] == "washington") echo "selected=selected"; ?> >washington</option>
This way you can get what u want.
And better use mysqli function for database interactions.
<option
<?php if ($value['city'] == delhi)
{
echo "selected = true";
} ?>
>delhi
</option>
Just het the selected value form db like
$choosen = $some value form db
then
$options = array(1 => 'data1', 2 => 'data2', 3 => 'data3');
foreach ($options as $key => $value)
{
echo '' . $value . '';
}
to get your selection box in php.I thnk you understand,it works for me

Multiple initially selected values in a dynamic select list with PHP

Thanks in advance for your help. This list is to update an existing record, so it's populated from a database with $rs_fullcat then checked with another recordset $rs_cat for the initially selected values. I can only get it to initially select one value, the first one in $rs_cat, but I need it to select all of the existing options from the database. I feel like I'm close but I can't find the answer anywhere. Here's the code:
<select name="category" multiple="multiple" id="category">
<?php
do {
?>
<option value="<?php echo $row_rs_fullcat['categoryID']?>"<?php if (!(strcmp($row_rs_fullcat['categoryID'], $row_rs_cat['categoryID']))) {echo "selected=\"selected\"";} ?>><?php echo $row_rs_fullcat['category_name']?></option>
<?php
} while ($row_rs_fullcat = mysql_fetch_assoc($rs_fullcat));
$rows = mysql_num_rows($rs_fullcat);
if($rows > 0) {
mysql_data_seek($rs_fullcat, 0);
$row_rs_fullcat = mysql_fetch_assoc($rs_fullcat);
}
?>
</select>
What you want to do, is first select (and fetch) all the selected ones from the database, and put them in a variable ($rs_cat in your case). Then, in your while loop it's a simple matter of doing an in_array() check to see if the value is selected.

Categories