I have a php file with 2 arrays in it
//script containing all the rublics and subrublics
$rublic[0]='rublic1';
$rublic[1]='rublic2';
$rublic[2]='rublic3';
$rublic[3]='rublic4';
$rublic[4]='rublic5';
$subrublic[0]='subrublic1';
$subrublic[1]='subrublic2';
$subrublic[2]='subrublic3';
$subrublic[3]='subrublic4';
$subrublic[4]='subrublic5';
?>
The elements of these arrays are shown in the drop-down box. What I need to do is to grab the element which the user chose from the box and write the index number of the choice selected into a database field. How could I do that?
I will post my code here even though I realize that my approach to this problem is completely wrong from the start :(
//add the index number of the rublic and the subrublic to the db
include('rublics.php');
if(isset($_POST[' article_type']) && ($_POST['article_type'] != '0')){
$rublic_selected = $_POST['article_type'];
for($count_rublic=0; $count_rublic<=10; $count_rublic++){
if($rublic_selected == $rublic[$count_rublic]) {
$rublic_selected = $count_rublic;
}
if($rublic_selected == $subrublic[$count_rublic]){
$rublic_selected = $count_rublic;
}
}
} else {
echo 'You did not make the selection. Please choose the type of the article.';
}
Your dropdown can/should use the index numbers for the value
attribute on the option
elements. Ie:
<select id="article_type" name="article_type">
<option value="0">rublic1</option>
<option value="1">rublic2</option>
<option value="2">rublic3</option>
<option value="3">rublic4</option>
<option value="4">rublic5</option>
</select>
Then when the form is POSTed to your PHP script, you will already have the correct index number to write to the database.
Try this, it should be a good start:
$rublic[0]='rublic1';
$rublic[1]='rublic2';
$rublic[2]='rublic3';
$rublic[3]='rublic4';
$rublic[4]='rublic5';
$subrublic[0]='subrublic1';
$subrublic[1]='subrublic2';
$subrublic[2]='subrublic3';
$subrublic[3]='subrublic4';
$subrublic[4]='subrublic5';
//$user_input = 'rublic3';
$user_input = 'subrublic4';
$options = array('rublic', 'subrublic');
foreach($options as $option_key => $option_value)
{
foreach($$option_value as $key => $value)
{
if($value == $user_input)
{
echo 'found it at ', $option_value, ' ', $key;
break;
}
}
}
Basically, I loop through both arrays until I find the string that matches the correct user input and return the name of the array it was found in (rublic or subrublic) plus the index of that array.