我會盡量縮短這個。最有可能我失去了一些明顯的東西,所以任何輸入將不勝感激。WHILE裏的IF語句 - PHP,MySQL和HTML下拉選擇
SQL結構/列:
id_user
(主鍵)income_input
income_select
PHP代碼:
<?php
$con = mysql_connect("localhost","dbname","pwd");
if (!$con)
{
die('Could not connect to the database: ' . mysql_error());
}
mysql_select_db("dbname", $con);
global $user; // Drupal 7 global
$userid = $user->uid; // Drupal 7 currently logged-in user id
$result = mysql_query("SELECT * FROM my_table WHERE id_user='$userid'");
if($result === FALSE) {
die(mysql_error());
}
if ($user->uid) {
?>
<form>
<label for="edit-1">Label</label>
<input id="edit-1" maxlength="60" size="60" type="text" value="<?php while($row = mysql_fetch_array($result)){ echo $row['income_input']; } ?>">
<select id="select-edit-1">
<option value="daily" <?php while($row = mysql_fetch_array($result)){ $income_select = $row['income_select']; if ($income_select == 'daily') echo 'selected="selected"'; }?>>Daily</option>
<option value="weekly" <?php while($row = mysql_fetch_array($result)){ $income_select = $row['income_select']; if ($income_select == 'weekly') echo 'selected="selected"'; }?>>Weekly</option>
</select>
</form>
<?php
}
mysql_close($con);
?>
從數據庫中正確提取輸入值(income_select
),但下拉(income_select
)不會返回所選狀態。如果我將整個表單包含到WHILE語句中,它可以正常工作,並且可以快速回顯數據庫值,並且選擇下拉列表「選定」狀態也可以正常工作。我會選擇這種方法,但我必須保持原樣,並且僅在當前登錄用戶有任何條目時才使用數據庫填充數據。
我希望上面的一個是有道理的,最後提前謝謝你的幫助!
這完美地工作。有一件事,我嘗試使用'fetch_assoc',但如果「當前登錄用戶」沒有以前的數據,表單根本不顯示。我使用'mysql_fetch_array'('$ row = mysql_fetch_array($ result);'),現在它工作正常。仍在進行一些測試,但這是一個真正的幫助。再次感謝! – Adrian
既然你想要一個關聯數組,assoc就是正確的選擇 - 但我想你應該首先使用'mysql_num_rows'來檢查是否有任何東西被選中,並且只有在它被獲取的時候。 – MightyPork
哦,好的,現在有道理。謝謝你的澄清。 – Adrian