2010-11-15 141 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帐户不安全。