检查数据库值是否与当前选择选项匹配的函数 [英] Function to check if the db value matches the current Select option
问题描述
我正在创建一个客户账户页面,该页面在数据库中显示相关信息并允许客户编辑他们的信息。下面的代码从数据库中检索并显示客户的帐户信息,并预先选择与其信息匹配的值,但由于有几百个select和/或multiselect元素,我想创建一个函数来检查db值(即 $ rows ['gift_privacy']
)与当前选项匹配。
<?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.phpmethod =post>
< option value =Standard<?php if($ row ['gift_privacy'] =='Standard')echoselected ='selected'; ?>>标准< /选项>
< option value =Gift_ID_Req<?php if($ row ['gift_privacy'] =='Gift_ID_Req')echoselected ='selected'; ?>>需要程序ID< / option>
< option value =Not_Enrolled<?php if($ row ['gift_privacy'] =='Not_Enrolled')echoselected ='selected'; ?>>请勿注册< / option>
< / select>
< input type =submitvalue =submit>
< / form>
编辑 - 对于多选元素,代码略有不同。元素名后跟方括号(即 name =notifications []
),并将值作为内插数组插入到数据库中 implode(',',$ _POST ['notifications'])
。然后,将这些逗号从提取的值中删除,以便正确地将它们与选项的值进行比较 $ row1 = str_replace(',','',$ row);
现有函数
此函数适用 selected =selected
改为正确的选项,但对于我来说使用这么多的元素太麻烦,我不知道如何修改代码,以便它可以很容易地应用到所有选择和/或多选元素。此外,由于页面当前使用标准选择元素和硬编码选项,我希望能够为每个元素都创建数组的解决方案。
$ b $
< select name =gift_privacy>
<?php
$ gifts = array(Standard=>Standard,Gift_ID_Req=>要求程序ID,Not_Enrolled=>不要注册 );
$ gift = $ row ['gift_privacy'];
foreach($ gifts为$ key => $ value){
if($ key == $ gift){
echo'< option selected =selectedvalue =' 。$ key。'>'。 $ value。'< / option>';
} else {
echo'< option value =''。$ key。'>'。 $ value。'< / option>';
}
}
?>
< / select>
我曾遇到同样的问题,一个函数(或一个类的静态方法)来处理我的选项列表。
为了打印出你的选项,你将不得不循环它们,所以当你循环时没有什么不好的,如果它必须是当前选中的每一个检查。
只需创建一个函数:
函数printSelectOptions($ dataArray,$ currentSelection){
foreach($ dataArray as $ key => $ value){
echo'< option'。 (($ key == $ currentSelection)?'selected =selected':'')。 'value =''。$ key。'>'。 $值。 < /选项>;
$ b给予$ dataArray
作为所选选项的键。
$> code>作为您的键/值选项数组,$ currentSelection
因此,在你的代码中,你只需要调用这个函数,如:
< select id ='mySelect'name = 'mySelect' >
<?php echo printSelectOptions($ gifts,$ gift); ?>
< / select>
这应该是可行的!
编辑:添加示例以选择多个...
<?php
$ options = array(1 =测试1,
2 =>测试2,
3 =>测试3);
$ selected = array(1,3);
函数printSelectOptions($ dataArray,$ selectionArray){
foreach($ dataArray as $ key => $ value){
echo'< option'。 (in_array($ key,$ selectionArray)?'selected =selected':'')。 'value =''。$ key。'>'。 $值。 < /选项>;
}
}
?>
<选择多个>
<?php echo printSelectOptions($ options,$ selected); ?>
< / select>
诀窍在于将所选值作为一组键而不是单个键传递。在示例中,我提供了虚拟数组,但很明显,您必须从数据库中构建自己的数组... ...)编辑:从该问题中选择多个数组。 ..
<?php
$ gifts = array(Standard=>Standard, Gift_ID_Req=>需要程序ID,Not_Enrolled=>不要注册);
$ gift = array($ row ['gift_privacy']);
函数printSelectOptions($ dataArray,$ selectionArray){
foreach($ dataArray as $ key => $ value){
echo'< option'。 (in_array($ key,$ selectionArray)?'selected =selected':'')。 'value =''。$ key。'>'。 $值。 < /选项>;
}
}
?>
<选择多个>
<?php echo printSelectOptions($ gifts,$ gift); ?>
< / select>
编辑:分解多个选定的值
如果你有多个选定的值作为一个逗号分隔的字符串,你只需要在传递给我提供的函数之前分解它...
$ selectedOptionsArray = explode(',',$ selectedOptionsString);
所以结尾代码看起来像......
<?php
$ gifts = array(Standard=>Standard,Gift_ID_Req=>需要程序ID,Not_Enrolled =>不要注册);
$ gift = explode(',',$ row ['gift_privacy']);
函数printSelectOptions($ dataArray,$ selectionArray){
foreach($ dataArray as $ key => $ value){
echo'< option'。 (in_array($ key,$ selectionArray)?'selected =selected':'')。 'value =''。$ key。'>'。 $值。 < /选项>;
}
}
?>
<选择多个>
<?php echo printSelectOptions($ gifts,$ gift); ?>
< / select>
I am creating a customer account page which displays the relevant information in the database and allows customers to edit their information. The code below retrieves and displays the customer's account information from the database and pre-selects the values matching their information, but since there are a few hundred select and/or multiselect elements I'd like to create a function which would check if the db value (i.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 code differs slightly for the multiselect elements. The element names are followed by square brackets (i.e.
name="notifications[]"
), and values are inserted into the database as imploded arraysimplode(',', $_POST['notifications'])
. Those commas are then stripped from fetched values in order to properly compare them to the option's values$row1 = str_replace(',', '', $row);
Existing Function
This function applies
selected="selected"
to the correct options, but it's too cumbersome for me to use with so many elements and I'm not sure how to modify the code so that it could be easily applied to all the select and/or multiselect elements. Also, since the page currently uses standard select elements with hard-coded options I'm hoping for a solution that doesn't require creating arrays for each element.<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>
解决方案I faced the same problem once and solved it by creating a function (or a class static method) to handle my option lists.
To print out your options you will have to cycle through them anyway, so while you cycle there is nothing bad in checking for each one if it must be the 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>'; } }
Giving
$dataArray
as your key/value options array, and$currentSelection
as the key of the selected option.So in your code you will have just calls to this function, like:
<select id='mySelect' name='mySelect'> <?php echo printSelectOptions($gifts, $gift); ?> </select>
This should do the work!
EDIT: Adding 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. In the sample I provided dummy arrays, but obviously you'll have to build yours from 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: Explode multiple selected values
If you have mutliple selected values as a comma separated string, you just have to explode it before passing to the function I provided...
$selectedOptionsArray = explode(',', $selectedOptionsString);
So the ending 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>
这篇关于检查数据库值是否与当前选择选项匹配的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!