Array of select values - php

So basically, I have an array of Modules and I want to have a drop-down menue that users can then select what grade they got. This works fine, however, I would like the results to be stored inside of an array, to however many values they selected. So for example:
If someone selected "40" in Mod1 and in Mod2 they selected "20" then the array would be like this:
mod1=>40
mod2=>20
...
Here is the code so far, it's probably something stupid, I just cannot get my head around it.
<?php
$modules = array('Mod1', 'Mod2', 'Mod3');
if(!isset($_POST['submitted']))
{
echo '<form method="post">';
echo 'Please enter the grades you got for each Module: <br />';
foreach($modules as $module)
{
echo $module . ': <input type="text" name="grades[]" value=""> <br />';
}
echo '<br /><input type="submit" name="submit" value="Go!">';
echo '<input type="hidden" name="submitted" value="TRUE">';
}else{
$input = $_POST['score[]'];
foreach($modules as $i => $module){
$input[$module] = $input[$i];
var_dump($input[$module] = $i);
//unset($input[$i]);
}
//var_dump($input);
}
?>

<select name="score[<?php echo $module; ?>]">
should get you going :)
the array will look exactly like you narrowed it down in the intro.

You could use a name that groups the values of the selects in POST into one array:
echo '<select name="score[]">';
You can then use:
$input = $_POST['score[]'];
foreach($modules as $i=>$module){
$input[$module] = $input[$i];
unset($input[$i]);
}
var_dump($input);

just change your name attribute to an array:
echo '<select name="score[]">';
the the $_POST variable will be in an array

Related

Drop down list in php only working as a default checkbox

I am trying to convert my search page from using a checkbox styled method to being able to use a drop down box to select each separate title header as a potential search option. However when converting this the title drop down box still acts as its old checkbox style, being that it only shows the data that is stored within the title name no matter which title is selected.
PHP Section:
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
// Set up our error check and result check array
$error = array();
$results = array();
// First check if a form was submitted.
// Since this is a search we will use $_GET
if (isset($_GET['search'])) {
$searchTerms = trim($_GET['search']);
$searchTerms = strip_tags($searchTerms); // remove any html/javascript.
if (strlen($searchTerms) < 3) {
$error[] = "Search terms must be longer than 3 characters.";
}else {
$searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection.
}
// If there are no errors, lets get the search going.
if (count($error) < 1) {
$searchSQL = "SELECT sid, sbody, stitle, sdescription FROM simple_search WHERE ";
// grab the search types.
$types = array();
$types[] = isset($_GET['body'])?"`sbody` LIKE '%{$searchTermDB}%'":'';
$types[] = isset($_GET['title'])?"`stitle` LIKE '%{$searchTermDB}%'":'';
$types[] = isset($_GET['desc'])?"`sdescription` LIKE '%{$searchTermDB}%'":'';
$types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked)
if (count($types) < 1)
$types[] = "`sbody` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked
$andOr = isset($_GET['matchall'])?'AND':'OR';
$searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `stitle`"; // order by title.
$searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}");
if (mysql_num_rows($searchResult) < 1) {
$error[] = "The search term provided {$searchTerms} yielded no results.";
}else {
$results = array(); // the result array
$i = 1;
while ($row = mysql_fetch_assoc($searchResult)) {
$results[] = "{$i}: {$row['stitle']}<br />{$row['sdescription']}<br />{$row['sbody']}<br /><br />";
$i++;
}
}
}
}
function removeEmpty($var) {
return (!empty($var));
HTML Section:
<body>
<?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm">
Search For: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /><br />
Search In:<br />
Body: <input type="checkbox" name="body" value="on" <?php echo isset($_GET['body'])?"checked":''; ?> /> |
Title: <form action="form_action.asp">
<select name="title">
<option value="Test Simple Search 1">Test Simple Search</option>
<option value="Searching Made Easy 101">Search Made Easy</option>
<option value="Gateway to Information">Gateway to Information</option>
<option value="The Gaming World as we Know it">Gaming World</option>
<option value="Hundreds of Ants Attacking">Ants Attacking</option>
<?php echo isset($_GET['title'])?"checked":''; ?> </select> |
Description: <input type="checkbox" name="desc" value="on" <?php echo isset($_GET['desc'])?"checked":''; ?> /><br />
Match All Selected Fields? <input type="checkbox" name="matchall" value="on" <?php echo isset($_GET['matchall'])?"checked":''; ?><br /><br />
<input type="submit" name="submit" value="Search!" />
</form>
<?php echo (count($results) > 0)?"Your search term: {$searchTerms} returned:<br /><br />" . implode("", $results):""; ?>
The option values that are used are the name as the titles stored within stitle within the mysql database. Have I simply implemented them wrong or is my php used after title completely incorrect?
Any advice on what I can do or any code snippets from yourselves would be very appreciated.
Ok I think I get your issue.
First if you want to select more than one item in a dropdown, then you need to add the multiple attribute to the select tag like this <select name="title" multiple>
Now when the user holds the CTRL key down and clicks entries, each clicked entry gets selected.
Secondly the data identifying the selected items will now be returned as an array in $_GET['title'] so if the first 2 options are selected the $_GET['title'] array would look something like this :-
0 - "Test Simple Search 1"
1 - "Searching Made Easy 101"
Now in order to re-select the items that were selected by the user when they submitted the form you have to set the selected="selected" attribute on each of the <option> tags that equate to the selected rows of the dropdown so they look selected when the user sees the form again.
<?php
function was_i_selected($selected_options, $value) {
if ( in_array($value, $selected_options, true) ) {
return 'selected="selected"';
} else {
return NULL;
}
}
?>
<select name="title" multiple>
<option <?php echo was_i_selected($_GET['title'], 'Test Simple Search 1');?> value="Test Simple Search 1">Test Simple Search</option>
<option <?php echo was_i_selected($_GET['title'], 'Searching Made Easy 101');?> value="Searching Made Easy 101">Search Made Easy</option>
<option <?php echo was_i_selected($_GET['title'], 'Gateway to Information');?> value="Gateway to Information">Gateway to Information</option>
<option <?php echo was_i_selected($_GET['title'], 'The Gaming World as we Know it');?> value="The Gaming World as we Know it">Gaming World</option>
<option <?php echo was_i_selected($_GET['title'], 'Hundreds of Ants Attacking');?> value="Hundreds of Ants Attacking">Ants Attacking</option>
</select>
Now that look very clumsy and we have not checked that $_GET['title'] actually exists, so I would probably do it like this :-
<?php
$options = array(
'Test Simple Search 1' => 'Test Simple Search',
'Searching Made Easy 101' => 'Search Made Easy',
'The Gaming World as we Know it' => 'Gaming World',
'Hundreds of Ants Attacking' => 'Ants Attacking'
);
<select name="title" multiple>
<?php
foreach ( $options as $val => $label ) {
if ( ! empty($_GET['title'] ) {
$sel = in_array($val, $_GET['title'], true) ? 'selected="selected"' : '';
echo '<option ' . $sel . ' value="' . $val . '">' . $label . '</option>';
} else {
echo '<option value="' . $val . '">' . $label . '</option>';
}
}
?>
</select>

Form: make a loop to save different value of a same field name

I do a form, inside I would like to do a loop for to show the same field. Each field will have different value and I would like to use sessions to take all the value.
Here is my code:
for ($i = 1; $i <= 5; $i++) { //normally not 5 but a random number, choose by user
echo "Numero ";
echo $i;
?>
<input type="text" name="number2" id="number2"/>
<?php
}
?>
</form>
<?php
echo $_POST['number2'];
$my_array=array($_POST['number2']);
$_SESSION['countnumb']=$my_array;
in another page:
foreach($_SESSION['countnumb'] as $key=>$value)
{
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
I can't register any number. How can I do this? thanks
Basics First - ids should be unique in a webpage.
Declaring <input type="text" name="number2" id="number2"/> in a loop is wrong.
For creating multiple input using loop try like this-
echo "<input type='text' name='number[$i]' id='number{$i}' />";
<input type="text" name="number[2]" id="number2"/>
would make $_POST['number'] an array which you can loop though server side, This is described here http://www.php.net/manual/en/faq.html.php#faq.html.arrays
foreach ($_POST['number'] as $number){
echo $number;
}
for example
this would make your code
for ($i = 1; $i <= 5; $i++) { //normally not 5 but a random number, choose by user
echo "<input type="text" name="number[$i]" id="number{$i}"/> ";
?>
<?php
}
?>
</form>
<?php
print_r( $_POST['number'] );
$_SESSION['countnumb']= $_POST['number'];

PHP Grab $_POST values without knowing values beforehand

A friend told my you can grab stuff from a general $_POST array, but I'm not getting it.
What I have are some values with unique row IDs pulled from a MySQL DB. I have them displayed so they can be updated if necessary en masse. I've given each input form a unique name by concat'ing the MySQL value, but I'm unsure how to grab those values in the script that accepts the $_POST values.
<form action"./" method="POST">
<?php
while($select_row = mysql_fetch_array($select_query))
{
echo $select_row['name'];
echo "</br>";
echo "Week ".$select_row['week'];
echo "</br>";
echo "Hours: ";
?>
<input class="options" type="text" name="hours<?php echo $select_row['submission_id']?>" value="<?php echo $select_row['hours']; ?>" />
<?php
echo "</br></br>";
?>
<input type="submit" value="Submit Hours">
</form>
<?php
}
?>
As you can see, each input will get a name like hours13 or hours144. Without knowing what they will be named beforehand, how can I extract them from $_POST?
Just iterate through the collection:
foreach($_POST as $key=>$value)
{
if($value != '')
{
echo "$key: $value\n";
}
}

how to loop and compare two arrays at the same time(PHP)

I have two array. What I want to do is compare the key ['user_id'] of two arrays, if they are the same, pass the ['user_id'] and ['ref'] in hidden form. I tried to put them into two foreach, but system seems into a dead lock.
<?php foreach($_SESSION['printing_set'] as $data) { ?>
<?php foreach(getProvenaMailableUserlist() as $userlist){ ?>
<input type="hidden" name="reference[<?php echo $data['user_id'] ?>]" value="<? if($userlist['user_id'] == $data['user_id']){echo $userlist['ref'];} ?>" />
<?php } ?>
<?php } ?>
What is the right way to do that?
What you are doing is printing again and again the part of '<input type="hidden" name="...'. here is what you should do
<?php
echo '<input type="hidden" name="reference[' . $data['user_id'] . ']" value="'; //olny one time.
foreach($_SESSION['printing_set'] as $data) {
foreach(getProvenaMailableUserlist() as $userlist){
if($userlist['user_id'] == $data['user_id']){
echo $userlist['ref']; //only if condition is true
}
}
}
echo '" />'; //only one time
?>
You've got some funky formatting going on, so it's hard to tell where the error might be. Try it like this:
<?php
foreach($_SESSION['printing_set'] as $data) {
foreach(getProvenaMailableUserlist() as $userlist){
$value = "";
if($userlist['user_id'] == $data['user_id'])
$value = $userlist['ref'];
echo "<input type='hidden' name='reference$user_id' value='$value' /> \n";
}
}
?>

How to pull out the values of ticked checkboxes using PHP?

while ($row= mysql_fetch_array($result, MYSQL_ASSOC))
{ $id=$row[id];
$html=<<<html
<tr><td>
<input style="float:left" type="checkbox" name="mycheckbox" value="$id">
<span style="float:left">$row[content]</span>
<span style="color:black;float:right">$row[submitter]</span></td></tr>
html;
echo $html;
}
Since the HTML code is generated dynamically, I don't know how long the array "mycheckbox" is and I don't know what checkboxes are ticked or unticked(This is determined by users). How to retrieve the values of ticked checkboxes using PHP?
The way you have it now, mycheckbox will get overwritten and act more like a radio button.
You probably want:
<input style="float:left" type="checkbox" name="mycheckbox[]" value="$id">
PHP will push the checked values into an array: $_GET['mycheckbox']
<?php
$values = $_GET['mycheckbox'];
$count = count($values);
echo 'Selected values are: <br/>';
foreach($values as $val) {
echo $val . '<br/>';
}
echo 'Total Length is: ' . $count . '<br/>';

Categories