Function to check if the db value matches the current select option

I am creating a customer account page that displays relevant information in the database and allows customers to edit their information. The code below fetches and displays the customer account information from the database and prefetches the values ​​that match their information, but since there are several hundred select items and / or multiselects, I would like to create a function that will check if the db will be a value (i.e. e. $rows['gift_privacy']

) matches the current option.

<?php   
try {  
$stmt = $conn->prepare("SELECT * FROM customer_info WHERE user_id = :user_id");  
$stmt->bindValue(':user_id', $user_id); 
$stmt->execute();
}catch(PDOException $e) {echo $e->getMessage();}
$row = $stmt->fetch();
?>
<form action="account_information-exec.php" method="post">
<select name="gift_privacy">
    <option value="Standard" <?php if($row['gift_privacy']=='Standard') echo "selected='selected'"; ?>>Standard</option>
    <option value="Gift_ID_Req" <?php if($row['gift_privacy']=='Gift_ID_Req') echo "selected='selected'"; ?>>Require program ID</option>
    <option value="Not_Enrolled" <?php if($row['gift_privacy']=='Not_Enrolled') echo "selected='selected'"; ?>>Do not enroll</option>
</select>
<input type="submit" value="submit">
</form>

      

Edit - . The encoding is slightly different for the multi selector items. The element names are followed by square brackets (i.e. name="notifications[]"

), and the values ​​are inserted into the database as mounted arrays implode(',', $_POST['notifications'])

. These commas are then removed from the selected values ​​to properly compare them with the option values$row1 = str_replace(',', '', $row);

Existing function

This function applies selected="selected"

on the correct parameters, but it is too cumbersome for me to use with many elements, and I'm not sure how to modify the code so that it can be easily applied to all selections and / or multi-element elements. Also, since the page currently uses standard select items with hard-coded options, I'm hoping for a solution that doesn't require creating arrays for each item.

<select name="gift_privacy">
    <?php
    $gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll");
    $gift = $row['gift_privacy'];
    foreach($gifts as $key => $value) {
    if($key == $gift) {
        echo '<option selected="selected" value="'. $key .'">'. $value .'</option>';
    } else {
        echo '<option value="'. $key .'">'. $value .'</option>';
    }
    }
    ?>
</select> 

      

+3


source to share


4 answers


I once ran into a problem and solved it by creating a function (or static class method) to handle option lists.

To print your options, you will still have to loop through them, so during the loop, there is nothing wrong with checking each one if it should be currently selected.

Just create a function like:

function printSelectOptions($dataArray, $currentSelection) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
    }
}

      

Providing $dataArray

as your parameter array the key / value and $currentSelection

as the key of the selected option.

So, in your code, you will only have calls to this function, for example:

<select id='mySelect' name='mySelect'>
    <?php echo printSelectOptions($gifts, $gift); ?>
</select>

      

This should do the job!

EDIT: Adding a sample to work with select multiple ...



<?php
$options = array(   1   =>  "Test 1",
                    2   =>  "Test 2",
                    3   =>  "Test 3");

$selected = array(1, 3);

function printSelectOptions($dataArray, $selectionArray) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
    }
}
?>

<select multiple>
    <?php echo printSelectOptions($options, $selected); ?>
</select>

      

The trick is passing the selected values ​​as an array of keys instead of a single key. I have provided dummy arrays in the sample, but obviously you will have to build your data from the database ... :)

EDIT: select multi with arrays taken from the question ...

<?php
$gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll");
$gift = array($row['gift_privacy']);

function printSelectOptions($dataArray, $selectionArray) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
    }
}
?>

<select multiple>
    <?php echo printSelectOptions($gifts, $gift); ?>
</select>

      

EDIT: Introduce multiple selected values

If you have mutliple selected values ​​as comma separated string, you just need to blow it up before going to the function provided to me ...

$selectedOptionsArray = explode(',', $selectedOptionsString);

      

So the final code will look like ...

<?php
$gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll");
$gift = explode(',', $row['gift_privacy']);

function printSelectOptions($dataArray, $selectionArray) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
    }
}
?>

<select multiple>
    <?php echo printSelectOptions($gifts, $gift); ?>
</select>

      

+2


source


To simplify this function, you can use a function like this:



<?php
function renderOption($key, $value, $current) {
    echo '<option value="' . $key . '"' . ($key == $current ? ' selected="selected"' : '') . '>' . $value. '</option>';
}
?>

<select name="gift_privacy">
    <?php
    $gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll");
    $gift = $row['gift_privacy'];
    foreach($gifts as $key => $value) 
        renderOption($key, $value, $gift);
    ?>
</select>

      

+1


source


Use a simpler method:

<?php
 echo '<option '.($key == $gift ? 'selected="selected" ' : '').'value="'. $key .'">'. $value .'</option>';
?>

      

Edit: second option

 echo '<option '.selected_option($key, $gift).'value="'. $key .'">'. $value .'</option>';

 function selected_option($val1, $val2){
  if($val1 == $val2){
   return 'selected="selected" ';
  }else{
   return '';
  }
 }

      

0


source


There is nothing wrong with what you have, and this, or something very similar, is the typical approach to this problem.

You could / could wrap it in an actual function, say print_select( $array, $selected );

that could / could print the whole thing <select>

, including the selection itself.

The final code could be:

print_select( $gifts, $selected_gift );
print_select( $colors, $selected_color );
// etc

      

-1


source







All Articles