2010-03-22 38 views
1

我有一個名爲post_tags的表列,稱爲posts,其中分配的標記被@符號分開存儲。我還有一個名爲標籤的表格,其中存儲了所有標籤名稱。我想以更標準化的方式設計我的數據庫,但爲了達到這個目的,我試圖做到這一點是最簡單的選擇。如何將mysql記錄顯示爲預選複選框?

不管怎樣,我想在屏幕上顯示從標籤表爲複選框的所有條目,所以我做的:

$query = mysql_query("SELECT * FROM tags ORDER BY name"); 

    while ($row = mysql_fetch_assoc($query)) { 

     $tag = $row['name']; 

     echo "<input type='checkbox' name='tags[]' value='$tag' />\n"; 

    } 

接下來,我想有分配給某個帖子被預選的標籤。舉例來說,如果我有在它下面的一個帖子是post_tags柱:

黨@海灘@海豚@

我想要的「黨」,「海灘」和「海豚」複選框默認選中(而其他選項的複選框未選中)。如何才能做到這一點?

+0

我不知道你想有一個像post_tags而不是使用一個路口表中的列。但是,如果你真的這麼做,你只需要在數據提取時進行更多的處理。 – 2010-03-22 20:45:28

回答

0

首先要做的是查看是否有任何現有數據。因此,運行查詢,並將該表格單元格的結果爲讓說$checkedstring如果沒有的話把你的默認字符串。

<?php 
$checkedstring = "[email protected]@[email protected]"; 
//Pull from DB if exsists and set $checkedstring to that value 
/// 
$checkeditems = explode ("@" , $checkedstring); 
$checked = array(); 
foreach($checkeditems as $item) 
{ 
    $checked[$item]=true; 
}  

$query = mysql_query("SELECT * FROM tags ORDER BY name"); 

while ($row = mysql_fetch_assoc($query)) 
{ 
    $tag = $row['name']; 
    $checkedstatus = ''; 
    if($checked[$tag]) 
    { 
     $checkedstatus = "checked='checked'"; 
    } 
    echo "<input type='checkbox' name='tags[]' value='$tag' $checkedstatus />\n"; 
} 


?> 
+0

謝謝sooooooooooooooooooooooo多!!! – Jennifer 2010-03-22 20:56:43

1

嘗試兩個結果和in_array()功能。

<?php 
$tags = mysql_query("SELECT * FROM tags ORDER BY name"); 
$post_tags = "[email protected]@[email protected]"; 
$arr_tags = explode("@", $post_tags); 

while ($row = mysql_fetch_assoc($query)) { 
    $check = in_array($arr_tags, $row['name'])? 'checked="checked"' : ""; 
    echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />'; 
    echo "\n"; 
} 
?> 

UPDATE 由於對性能傑夫問題,我找了更快的解決方案,並使用isset()更快所以這會做值的更快查找。該array_flip()是徵稅3時間小於in_array()

<?php 
$tags = mysql_query("SELECT * FROM tags ORDER BY name"); 
$post_tags = "[email protected]@[email protected]"; 
$arr_tags = array_flip(explode("@", $post_tags)); 

while ($row = mysql_fetch_assoc($query)) { 
    $check = isset($arr_tags[$row['name']])? 'checked="checked"' : ""; 
    echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />'; 
    echo "\n"; 
} 
?> 
+0

in_array函數的開銷是多少?它每次都掃描整個陣列嗎? – 2010-03-22 23:58:27

+0

我在我的機器上用中等大小的查詢結果進行了測試,運行時間爲0.25秒 – 2010-03-23 14:34:09

+0

當我更加註意in_array時,您的更新看起來不錯,它會每次掃描循環中的數組,以便標籤#有問題,但翻轉和isset似乎好多了。 – 2010-03-28 16:38:05