2013-02-22 75 views
0

填充複選框,在我的MySQL數據庫我有一個這樣的表:從MySQL數據庫

Column  Value 
---------------------------------- 
Id   int pk autoinc 
Name  varchar(50) 
Choices  set('a', 'b', 'c', ...) 
...   ... 

當這個數據正在更新,我希望有很多與每個複選框顯示覆選框代表的一員選擇。在PHP與此類似創建每個複選框:

echo "<input type=Checkbox name=$choiceName[i] value=$choiceName[i]>" 

我的問題是如何創建這些複選框並填充它們(由被檢查或不)在表中一個特定的ID。

+1

[你有什麼試過?](http://www.whathaveyoutried.com/)請參閱[問問建議](http://stackoverflow.com/questions/)請諮詢)。 – 2013-02-22 20:04:41

+0

你甚至做過任何研究嗎? SO不是「給我」的地方。這有助於發生錯誤。 – UnholyRanger 2013-02-22 20:07:23

+0

這是什麼數據庫?你如何呈現HTML表單複選框?有沒有辦法幫助你沒有細節...... – ducin 2013-02-22 20:07:54

回答

4

我終於找到了解決方案。

爲了獲得set數據類型的列Choice中的允許值。你必須做以下事情:

$result = mysql_query("SHOW COLUMNS FROM Table LIKE 'Choice'"); 
    $line = mysql_fetch_array($result); 
    //Remove the unwanted characters from the Type 
    $set = substr($line['Type'],5,strlen($line['Type'])-7); 
    //An array containing all allowed members from the Choice set 
    $choices = preg_split("/','/",$set); 

    $result = mysql_query("SELECT * FROM Table WHERE Id=$someId"); 
    $row = mysql_fetch_row($result); 
    $selected = explode(',', $row[$indexOfChoicesColumn]); 
    $j=0; 
    for($i=0; $i<count($days); $i++){ 
    if($j<count($selected) && $selected[$j] == $choices[$i]){ 
     echo $choices[$i]." <input type='checkbox' name='choices[]' value='". $choices[$i] ."' checked> "; 
     $j++; 
    } 
    else echo $choices[$i]." <input type='checkbox' name='choices[]' value='". $choices[$i] ."'> "; 
    } 
0

實施例:

//or you can obtain $choices = $row['Choices']; from your DB, its the same 

$choices = "Example1,Example4,Example10"; 
$arrChoices = explode(',', $choices); 

foreach ($arrChoices as $key => $value) { 
echo "<input type='checkbox' name='$value' value='$value'/>"; 
} 

Saludos)

+0

我需要直接從集合中獲取選擇,而不是對它們進行硬編碼。 – 2013-02-22 20:33:47

+0

讓我看看你的數據表中的選擇示例;) – Hackerman 2013-02-22 20:34:34

+0

它們都是字符串。 – 2013-02-22 20:37:05