php array for each in for each - php

I am trying to get a select list with values from $staff
The bit i am struggling is selecting the staff that are already enrolled from $entry->enrolments.
If the $staff id exists in $entry->enrolments select it in the select list
$entry = Record from mysql
$staff = list of staff in an array.
$entry->enrolments = comma seperated values of enrolled staff
<select name="tutor[]" id="tutor" multiple="multiple" size="5" class="required" title="Select Staff">
<?php
$entry = get_record("staff_development", "id", $id);
$staff = get_records("user", "deleted", "0", "lastname ASC", "id,firstname,lastname,idnumber");
$sdenrolments=array($entry->enrolments);
$people = explode(",", $entry->enrolments);
foreach($staff as $tutor){
foreach($people as $person){
if($tutor->id>1)echo '<option value="'.$tutor->id.'"';
if ($person==$tutor->id) {echo 'selected="selected"';}
echo '>'.$tutor->lastname.' '.$tutor->firstname.'</option>';
}
}
?>
</select>
Any help/guidance would be greatly appreciated.
Thanks in advance

in_array is the easiest way to tell if a value is in an array :) Replace your loops with this:
foreach($staff as $tutor){
echo '<option value="'.$tutor->id.'"';
if(in_array($tutor->id, $people))
echo 'selected="selected"';
echo '>'.$tutor->lastname.' '.$tutor->firstname.'</option>';
}
You might also want to rename your variable from people to enrolled_staff or something a bit more clear.

Your if block is confusing. You are checking for $tutor->id > 1 when opening the option tag, but aren't when closing it. PaulP.R.O mentions in_array which you should replace your foreach loops with. Here is your if block cleaned up and set the check for selection inline.
if($tutor->id > 1) {
echo '<option value="'.$tutor->id.'" ' . (($person==$tutor->id) ? ' selected="selected"': '') . '>';
echo $tutor->lastname.' '.$tutor->firstname;
echo '</option>';
}

Related

Making Select Boxes Have Database Entry Set As Selected in PHP

How would I go about setting the "selected" attribute to one of these boxes, based on what value is stored in the $genre variable?
i.e. If $genre == "Puzzle" then
<option value=Puzzle>
becomes
<option value=Puzzle selected>
Here is my current code:
<?php
$query = "SELECT * FROM release_dates WHERE id = $id";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$genre = $row['game_genre'];
?>
<select name=genre>
<option value=Action>Action</option>
<option value=Adventure>Adventure</option>
<option value=Puzzle>Puzzle</option>
<option value=RPG>RPG</option>
<option value=Horror>Horror</option>
<option value=Shooter>Shooter</option>
<option value=Simulator>Simulator</option>
<option value=Sport>Sport</option>
<option value=Strategy>Strategy</option>
</select>
Also, for extra brownie points, how would this apply to select boxes with the "multiple" attribute?
Any help or ideas would be greatly appreciated.
Well, that's pretty simple actually:
<option value=Action <?php $genre == "Action" ? "selected":""?> >Action</option>
Just use a ternary operator (condition) ? true:false to input "selected" if the value is set. Simply duplicate that logic on all the options:
<option value=Action <?php $genre == "Action" ? "selected":""?> >Action</option>
<option value=Adventure <?php $genre == "Adventure" ? "selected":""?> >Adventure</option>
<option value=Puzzle <?php $genre == "Puzzle" ? "selected":""?> >Puzzle</option>
<option value=RPG <?php $genre == "RPG" ? "selected":""?> >RPG</option>
Hope that helps!
You could use a foreach loop to iterate over your options, and each time, perform a check using an if statement to see if it matches:
foreach ($genres as $genre) {
if ($genre === "Puzzle") {
echo '<option value="'.$genre.'" selected>'.$genre.'</option>';
else {
echo '<option value="'.$genre.'">'.$genre.'</option>';
}
}
By the way, you shouldn't be using mysql_* functions anymore as they are unsafe, deprecated, and will be removed from PHP in the future. Take a look at PDO.
<option value="Strategy" <?php if($genre == "Strategy"){ echo 'selected="selected"';} ?> >Strategy</option>
I came up with a version that keeps everything in PHP
<?php
$query = "SELECT * FROM release_dates WHERE id = ". $id;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
// possible options
$genre_options = array(
'Action'
'Adventure'
'Puzzle'
'RPG'
'Horror'
'Shooter'
'Simulator'
'Sport'
'Strategy'
);
// loop over the options, and wrap them in tags
$options = '';
foreach ($genre_options as $genre) {
// check if we have a match
$selected = '';
if ($genre == $row['game_genre']) {
$selected = 'selected="selected"';
}
$options .= '<option value="'. $genre .'" '. $selected .'>'. $genre .'</option>'
}
echo '
<select name=genre>
'. $options .'
</select>
';
?>
What this does is create an array of possible genre's, loop over them, and see if any of them match the genre that was returned from the query. If thats the case it will add the selected="selected" attribute.
Unfortunately I'll be missing out on the "brownie points", because I'm not able to help you with the multi-select.
Let me know if this helps!
EDIT: I also noted that in your query you where passing the $id variable as a string. Fixed that in the query in my example.
Instead of defining your genres using plain HTML, create an array with all your genres.
To do so:
$genres = array(
"Action",
"Adventure",
"Puzzle",
"RPG",
"Horror",
"Shooter",
"Simulator",
"Sport",
"Strategy"
);
foreach($genres as $currentGenre) {
echo "<option value="'.$currentGenre.'" '.($currentGenre == $genre ? "selected" : "").'>'.$currentGenre.'</option>';
}
What this does, is loop over all your genres and create a single <option> for each of them. If the $currentGenre (so one of the genres from the array $genres) matches $genre (which you pulled from MySQL), it selects that option using a inline if-statement.

How to dynamically get the value of a select tag from MySQL table

Thanks for dropping by and I'm sorry if this question seems to be easy as I'm kinda new to php. Im trying to do a school project and my problem now is that I cant seem to get the values of the dropdown. I have been trying to search in every forum and some similar questions in here but they seem to only show how i can populate the dropdown with database values.
The code for populating the dropdown menu is working, but recording the selected value is not working for me.
Here is my php code for the dropdown:
<div class="panel">
<label class="panelname">Category:</label>
<select name="category" class="signup_field">
<option>Select One</option>
<? // retrieve all the categories and add to the pull down menu
$query = 'SELECT category_id, name FROM category ORDER BY name ASC';
$request = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($request, MYSQLI_NUM)) {
$cat_id = $row[0];
echo "<option value=\"row[0]\"";
//check for stickyness:
if (isset($_POST['category']) && ($_POST['category'] == $row[0])) {
echo ' selected="selected"';
//$_POST[]
} echo ">$row[1]</option>\n";
}
?>
</select>
<? if (array_key_exists('category', $add_product_errors)) echo '<label class="error">' . $add_product_errors['category'] . '</label>'; ?>
</div>
and here is my part of my code for validation: -
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Check for a category:
if (!isset($_POST['category']) || !filter_var($_POST['category'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
$add_product_errors['category'] = 'Please select a category!';
}
..... // other codes for validation (Eg: if (empty($add_product_errors)) { proceed to query} )
I don't know what seems to be the problem but there are no values recorded in the $_POST['category'] for me to save into MySQL and I keep getting the Please select a category error.
Thank you all for your help. :)
your problem seems to be echo "<option value=\"row[0]\"";. You want to replace it with
echo "<option value=\"$row[0]\"";
echo "<option value=\"row[0]\""; just puts a String row[0] there
Thanks, I seem to have solve the problem ..
I have seemed to have deleted the ($)row in the row[0] for it to be read properly.
just put $ on the row[0]:
echo "<option value=\"row[0]\"";
I used to solve this problem like ... In your case.
while ($row = mysqli_fetch_array($request, MYSQLI_NUM)) {
$cat_id = $row[0];
$str = null;
if (isset($_POST['category']) && ($_POST['category'] == $row[0])) {
$str = 'selected="selected"';
}
echo '<option value="'.$row[0].'" '.$str.'>'.$row[1].'</option>';
}

Dropdown Menu to Query Database

First of I apologize if this is a dumb question - I'm just starting to pick up my php/mysql skills. I'm making a dropdown form with 3 dropdowns. I want to be able to trigger a query from the form. You select Part Type, Make, Model hit submit and a table of results is displayed.
I have my form populated with 3 arrays and when you hit submit, I can echo the key of each selected item to the page:
echo '<form action="dbBrowse.php" method="post">';
$mak = array (0 => 'Make', 'Ford', 'Freightliner', 'Peterbilt', 'Sterling', 'Mack', 'International', 'Kenworth', 'Volvo');
$mod = array (0 => 'Model', 'Argosy', 'Midliner');
$p = array (0 => 'Part', 'Radiator', 'Charge Air Cooler', 'AC');
echo '<select name="drop1">';
foreach ($p as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '</select>';
echo '<select name="drop2">';
foreach ($mak as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '<select name="drop3">';
foreach ($mod as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '</form>';
//echo keys of selection
echo $_POST['drop1'];
echo "<br />";
echo $_POST['drop2'];
echo "<br />";
echo $_POST['drop3'];
//these echo something like 1, 1, 3 etc. to my page
Where I'm getting lost is I'm looking to take the selected options and insert them into a query something like this:
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" . AND WHERE make = "$makeTypeVar" . AND WHERE model = "$modelTypeVar"');
$partTypeVar being the corresponding value to the key that is being returned from the array.
I'm driving myself crazy trying to figure out how to make that happen. Eventually I want to expand this further but just being able to create a mysql statement with the values selected would make my day right now. I understand the concept of what needs to happen but I'm unsure of how to accomplish it. Any help or pushes in the right direction would be greatly appreciated.
First of all, you have to delete the . char in your SQL query, there's no need to use it for now and of course assign the correct values to the variables.
$partTypeVar = mysql_real_escape_string($_POST['$drop1']);
$makeTypeVar = mysql_real_escape_string($_POST['$drop2']);
$modelTypeVar = mysql_real_escape_string($_POST['$drop3']);
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" AND WHERE make = "$makeTypeVar" AND WHERE model = "$modelTypeVar"');
I am assuming that's the correct order of your variables.
I hope this help!
If I've understood your question, when the form is submitted, you want to query the database with the selected values.
Example using AND:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' AND make='%s' AND model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match those three values.
Example using OR:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' OR make='%s' OR model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match any of those three values.
You can read more about this:
mysql_query
mysql_real_escape_string
MySQL 5.6 Reference Manual :: 12 Functions and Operators :: 12.3 Operators
<select name="myFilter">
<option value="Chooseafilter" name="default">Choose a filter...</option>
<option value ="Lastname" name="opLastName">Last Name</option>
<option value="Firstname" name="opFirstName">First Name</option>
<select>
<li><!--TEXT SEARCH INPUT--><input type="text" name="search_filter" /></li>
...
dbconnection();#assume that all connection data is here
...
$filter = $_POST['myFilter']; #
...
switch($filter)
{
case "Lastname":
$selectedoption = "profile_name";
break;
case "Firstname":
$selectedoption="profile_first_name";
break;
case "Chooseafilter":
$selectedoption = "";
break;
}
$result = pg_query($db_con, "SELECT * FROM profile WHERE ".$selectedoption." LIKE'%$_POST[search_filter]%'");
$row = pg_fetch_assoc($result);
if (isset($_POST['submit']))
{
while($row = pg_fetch_assoc($result))
{
echo"<ul>
<form name='update' action='' method='POST'>
<li>Guest Last Name:</li>
<li><input type='text' name='profile_name_result' value='$row[profile_name]' /></li>
<li>Guest First Name:</li>
<li><input type='text' name='profile_first_name_result' value='$row[profile_first_name]' /></li>
<li><input type='submit' value='Update' name='update'></input></li>
...

Need help pulling into multiple columns from one database table - mysql_query

Afternoon all,
A very quick question... a friend has set up a form for me using mysql_query. Since he wrote this, I have added an extra column into the database, which I want to pull through into the form.
However I can't seem to get this extra column to appear (labelled Currency). The reason I need it is the query below will pulls back a value and the £ symbol. Because I want to display not only £, but also € prices, I need this extra column to pull through (obviously I will have to remove the £ from the echo below too).
I've tried adding the extra column (Currency) to the code, e.g. "SELECT Room, Currency, Price FROM Spa_Upgrades
but this hasn't worked.
The code is:
<?php
if (isset($id))
{
$query2 = mysql_query("SELECT Room, Price FROM Spa_Upgrades WHERE Spa_Upgrades.Spa_Id = '".$id."' AND Spa_Upgrades.Id = '".$pack."' order by Spa_Upgrades.Order");
$rows = mysql_num_rows($query2);
if($rows==0) {echo "disabled='disabled'/>";}
else
{
echo "/>";
echo "<option value='Default'>Please Select</option>";
for($i=0; $i<$rows; $i++)
{
$result2 = mysql_fetch_array($query2);
echo "<option value='".$result2[0]." £".$result2[1]."pp'>$result2[0] £$result2[1]pp</option>";
}
}
}
Hugely grateful if someone can solve this!
Thanks,
Motley
Alter the query as follows:
SELECT Room, Price, Currency FROM Spa_Upgrades ...
Alter the line beginning echo inside the for loop: replace £ with $result2[2] wherever it appears. (Or if the Currency column doesn't contain the HTML entity for the currency symbol, then replace £ with appropriate code to obtain the symbol from the Currency column entry.)
You also need to add the column to the output... I would also switch to an associative array otherwise if you add a column and its not at the end you have to change all the indexes.
if (isset($id))
{
$query2 = mysql_query("SELECT Room, Price, Currency FROM Spa_Upgrades WHERE Spa_Upgrades.Spa_Id = '".$id."' AND Spa_Upgrades.Id = '".$pack."' order by Spa_Upgrades.Order");
$rows = mysql_num_rows($query2);
if($rows==0) {echo "disabled='disabled'/>";}
else
{
echo "/>";
echo "<option value='Default'>Please Select</option>";
for($i=0; $i<$rows; $i++)
{
$result2 = mysql_fetch_assoc($query2);
$value = $result2['Room'] . ' ' . $result2['Currency'].$result2['Price'].'pp';
echo sprintf('<option value="%s">%s</option>', $value, $value);
}
}
}
Use mysql_fetch_assoc() instead of mysql_fetch_array()
A good practice as well is to separate data retrieving from display logic
Try this:
<?php
$results = array();
if (isset($id))
{
$resource = mysql_query("SELECT room, currency, price FROM Spa_Upgrades
WHERE Spa_Upgrades.Spa_Id = '".intval($id)."' AND Spa_Upgrades.Id = '".intval($pack)."'
order by Spa_Upgrades.Order");
while($row = mysql_fetch_assoc($resource))
$results[] = $row;
}
?>
<select name="..." <?php echo (count($results) > 0 ? '' : 'disabled') ?>>
<option value="Default">Please Select</option>
<?php
foreach($results as $result)
{
$value = $result['room'].' '.$result['currency'].$result['price'].'pp';
echo '<option value="'.htmlspecialchars($value).'">'.htmlspecialchars($value).'</option>'."\n";
}
?>
</select>

php multiple select drop down

here is my mysql and php code layout:
I have 3 tables
tableA stores unique "person" information
tableB stores unique "places" information
tableC stores not unique information about a person and places they have "beenTo".
here is how i layed out my form:
-one big form to insert into "person" tableA; "beenTo" tableC
in the form, a person mulitple selects "places" which get inserted into "beenTo"
my question is, when i am editing a "person" how do i display what the user has already selected to appear on my multiple select options drop down menu?
my drop down menu at the moment query "places" table and displays it in a multiple select drop down menu. its easier when a person have beenTo one place, the problem arrises when there is more than one "beenTo" places?
Foreach option, check if they have beenTo it. Then add the selected="selected" attribute to the tag if true.
Example:
<select multiple="multiple">
<option selected="selected">Rome</option>
<option>France</option>
<option selected="selected">Underpants</option>
</select>
And in PHP this might look like:
$beenTo = array("Rome","Underpants");
$places = array("Rome","France","Underpants");
?> <select multiple="multiple"> <?php
foreach($places as $place) {
echo "<option";
$found = false;
foreach($beenTo as $placeBeenTo) {
echo "value='$place'";
if ($placeBeenTo == $place) {
$found == true;
echo " selected=\"selected\" ";
break;
}
}
if (!$found) echo ">";
echo $place . "</option>";
}
?> </select> <?php
There's probably a much more efficient way to do this.
For clarification, you will want to have a name attribute for your select tag which allows for multiple selected options to function correctly.
<form method="post" action="">
<select name="places[]" multiple="multiple">
<?php
$_POST += array('places' => array());
$places = array('fr' => 'France', 'cn' => 'China', 'jp' => 'Japan');
$beenTo = array_flip($_POST['places']);
foreach ($places as $place => $place_label) {
$selected = isset($beenTo[$place]) ? ' selected="selected"' : '';
echo '<option value="' . $place . '"' . $selected . '>' . $place_label . '</option>';
}
?>
</select>
<input type="submit" value="Save Changes" />
</form>
<option id = 'example' <? if ($_POST['example']) echo 'selected' ?>>
But you'll be using a $_SERVER['cookies'] or other cache to store the past visits, not the $_POST array.. edit with extreme predjudice

Categories