[英]Store dropdown in mysql database
在數據庫中存儲選擇框選項的最佳方法是什么? 我需要將所有選項存儲在單個列字段中。 用戶將被允許為自定義字段創建自己的自定義下拉選項,我不確定如何保存所有選項以使用php從mysql動態地構建它。 任何幫助將不勝感激。
您可以將選擇選項作為JSON存儲在數據庫中。 為此,您可以在options數組上使用json_encode
,然后將值存儲在數據庫中。
// an array of options
$opts = array('An option', 'Another option', 'A third option');
// json encode the array for storage in the database
$dbValue = json_encode($opts);
// your code to save in the database goes here
要檢索選項,可以使用json_decode
將其轉換回選項數組。
// your code to retrieve the value from the database goes here
// json decode the array stored in the database
$out = json_decode($dbValue);
// output the select
echo '<select>';
// loop through the options and output
foreach ($out as $opt)
{
echo '<option>'.$opt.'</option>';
}
echo '</select>';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.