2010-11-15 107 views
0

我想用數據庫中的表名填充列表框。這裏是我爲它編寫的代碼,但它似乎並不工作使用表名填充列表框

<select id="arrays" name="arrays" style="width: 403px;" class="Fieldcell"> 
<?php 
$dbname = 'myBase'; 

if (!mysql_connect('localhost', 'root', '')) { 
    echo 'Could not connect to mysql'; 
    exit; 
} 

$sql = "SHOW TABLES FROM $dbname"; 
$result = mysql_query($sql); 

if (!$result) { 
    echo "DB Error, could not list tables\n"; 
    echo 'MySQL Error: ' . mysql_error(); 
    exit; 
} 

$num_tables = mysql_num_rows($result); 


for($i=0;$i<$num_tables;$i++) 
{ 

echo "<option value=\"$row[i]\">$row[i]</option>"; 

} 

/*while ($row = mysql_fetch_row($result)) { 

echo <option value=\"$row[0]\">$row[0]</option>"; 

}*/ 


mysql_free_result($result); 
?> 
</select> 
+1

'它似乎沒有工作'。你能解釋什麼不起作用嗎?您可以輕鬆地在屏幕上打印PHP警告/錯誤。但是我能看到的是你的第一個for循環並不完整。 'for($ i = 0; $ i'應該是:for($ i = 0; $ i <$ num_tables; $ i ++) – Rhapsody 2010-11-15 13:22:27

回答

2

註釋掉的部分是使它工作的部分。您正在使用for循環,您正試圖循環通過從未定義的變量$行。您需要使用mysql_fetch_row()來實際獲取結果集中的數據。它看起來像你有,但後來評論說。消除這個lop並取消註釋while循環。雖然看起來像你在while循環中有語法錯誤(缺少引號)。下面是它應該是什麼樣子:

while ($row = mysql_fetch_row($result)) { 
    echo "<option value='{$row[0]}'>{$row[0]}</option>"; 
} 

OR

你可以保持它現在的樣子,但你上面的for循環需要添加

$row = mysql_fetch_all($result); 
+0

感謝您的快速回復,問題已解決,並按預期工作。 – George 2010-11-16 09:20:37

0
<?php 
echo '<select id="arrays" style="width: 403px;" class="Fieldcell">'; 
mysql_connect('localhost','root','') or die('Could not connect to mysql'); 
$result = mysql_query("SHOW TABLES FROM $dbname") or die("DB error, could not list tables<br />MySQL error: ".mysql_error()); 
while($r = mysql_fetch_row($result)) { 
    echo '<option value="'.$r[0].'">'.$[0].'</option>'; 
} 
echo '</select>'; 
?> 

嘗試這個。

0

試試這個:

mysql_connect('localhost','root','pass'); //dont forget the correct password 
$dbname=???; // insert the database name here 
$thequery=mysql_query("SELECT * FROM $dbname"); 
echo '<select id="arrays" name="arrays" style="width: 403px;" class="Fieldcell">'; 
while($currow=mysql_fetch_array($thequery)) { 
    echo '<option value="'.$currow(COLUMN NAME HERE).'">'.$currow(COLUMN NAME HERE).'</option>'; //insert the column name (the one that has the values inside) 
} 
echo '</select>'; 

在一個側面說明:它不是一個好主意,使用該數據庫爲根。使用root帳戶不安全。