2013-08-20 47 views
0

動態值HTML選擇元素這裏是我的數據:使用從MySQL

select * from extension; 
+---------+-------+ 
| ext_num | name | 
+---------+-------+ 
| 574324 | joe | 
| 564334 | sarah | 
| 987652 | pete | 
+---------+-------+ 
3 rows in set (0.00 sec) 

我試圖插入

selected="selected" 

動態,同時通過表循環。

<?php 

$mysqli = new mysqli("localhost", "user", "pass", "db"); 
if ($mysqli->connect_errno) { 
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; 
} 

if ($result = $mysqli->query("SELECT * FROM extension")) { 
print "<select>\n<option>select a value</option>\n"; 
    while ($row = $result->fetch_assoc()) 
{ 
     printf ("<option value=\"%s\">%s</option>\n", $row["ext_num"], $row["name"]); 
    } 
print '</select>'; 
} 
?> 

什麼是實現以下最簡單的/有效的方法:

<option value="987652" selected="selected">pete</option> 

:使用類似於上面的代碼(尤其是選擇= 「選擇」)

到我的循環?

+2

你在哪兒,指定「皮特」應該是數據選擇? – Pankrates

+0

@Pankrates這可能來自表單提交或$ _POST。我需要更多數據嗎? – cookie

回答

0

好的假設你從POST得到被選中行,你可以把一個條件在while循環,檢查的具體變量後

<?php 

    $name = $_POST['name']; 

    while ($row = $result->fetch_assoc()) 
    { 
     if ($name==$row["name"]) 
      echo '<option value="'.$row["ext_num"].'" selected="selected">'.$row["name"].'</option>'; 
     else 
      echo '<option value="'.$row["ext_num"].'">'.$row["name"].'</option>'; 
    } 
?> 
0

您可以通過用戶驗證碼:

<?php 

$mysqli = new mysqli("localhost", "cookie", "pass", "test_intranet"); 
if ($mysqli->connect_errno) { 
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; 
} 
$selItem = 987652 ; 
if ($result = $mysqli->query("SELECT CONCAT('<option value=\"',`ext_num `,'\" ',IF(ext_num=$selItem,'selected=\"\"',' '),'>',`name`,'</option>') AS 'row' FROM extension")) { 
print "<select>\n<option>select a value</option>\n"; 
    while ($row = $result->fetch_assoc()) 
{ 
     echo $row['row'] ; 
    } 
print '</select>'; 
} 
?> 

更多的性能和用途選擇=「」,在不斷的查詢。