将数据库中的所有表显示为php中的选择表单

时间:2014-10-25 15:40:25

标签: php mysql mysqli

HIHO, 我在页面上以表格形式显示所有表名时遇到了一些问题。

代码如下:

<select name="users" onchange="showTables(this.value)">
<option value="">Select a table:</option>';
$result = mysql_list_tables($db_name);
for ($i = 0; $i < count(mysql_num_rows($result)); $i++){
echo '<option value="' . mysql_tablename($result, $i) . '">' . mysql_tablename($result, $i) . '</option>';
}
echo '</select>
</form>
<br> 
<div id="tablesDb"><b>All content from selected table will be listed there.</b></div></div>';

我也尝试使用mysqli,但是我得到了结果,但仍然没有表格的名称,没有任何东西可供选择。

也许有人知道如何开展这项工作。

3 个答案:

答案 0 :(得分:0)

首先,您肯定希望使用MySQLi,因为不推荐使用MySQL扩展。其次,您可以在简单的SELECT查询中获取所需的所有数据,如下所示:

select `TABLE_NAME` from information_schema.tables

答案 1 :(得分:0)

试试这个

$mydbname = 'database_name';
$con=mysqli_connect("localhost","my_user","my_password",$mydbname);
// Check connection
if (mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit();
}

$options = '';

 // for the query you can use two of the following lines (line1+line2  OR line3+line4)
//Use line (line1+line2)
$result = mysqli_query($con,"SHOW TABLES");
$column_name ='Tables_in_'.$mydbname;

// OR (line3+line4
$result = mysqli_query($con,"SELECT TABLE_NAME AS tbl FROM information_schema.tables" WHERE TABLE_SCHEMA = \"'.$mydbname.'\"; ");
$column_name ='tbl';


while($row = mysql_fetch_array($result))
    $options .= '<option value="' . $row[$column_name] . '">' . $row[$column_name] . '</option>';


echo '<select name="users" onchange="showTables(this.value)">';
echo '<option value="0">Select a table:</option>';
echo  $options;
echo '</select>';

答案 2 :(得分:0)

我将代码修改为:

 <select name="db_tablelist" onchange="showTables(this.value)">
 <option value="">Select a table:</option>';
 $result = mysqli_query($con,"SHOW TABLES");
 while($row = mysqli_fetch_array($result)) { echo '<option value="' . $row[0] . '">'.$row[0].''; } echo '';
 echo '</select>
 </form>
 <br>
 <div id="tablesDb"><b>All content from selected table will be listed there.</b></div></div>';

现在一切正常。