douna4762 2015-05-05 11:13
浏览 37
已采纳

根据之前的选择选择字段

I am trying to populate a select dropdown from a previous select field (on the same page)

The first select, shows table names from a MYSQL db. The second select should show column names from the selected table

Here is my code

page.php

<label class="">Select a Database Table</label>
 <select class="full-width" data-placeholder="Select Table" data-init-plugin="select2" onchange="showColumn(this.value);">
  <optgroup label="Table">

<?php

   $table_count = mysql_query("SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = 'cl49-vclients'"); 

    $tables = array();
    while($row = mysql_fetch_array($table_count))
    { ?>
  <option value="<?php echo $row["TABLE_NAME"]; ?>"><?php echo $row["TABLE_NAME"]; ?></option>
<?php
   }
?>
 <!-- </optgroup>-->
</select>
<script>
function showColumn(tablename)
{
    if(tablename !='')
    {
        $.ajax({ 
            type:"POST",
            url :"ajax.php"; 
            data:{tablename:tablename},
            success:function(data){
                alert(data); //This will alert column name comma separated  
            }       
        });
    }
}
</script>

ajax.php

<?php
//make database connection
$column_count = mysql_query("SHOW COLUMNS FROM '".$_POST['tablename']."'"); 
    $columns = array();
    while($columnRow = mysql_fetch_array($column_count))
    {
        $columns[] = $columnRow['Field'];
    }   
    echo implode(',',$columns); //This will return column name comma separated 
?>

<label class="">Table</label>
  <select class="full-width" data-placeholder="Select Table" data-init-plugin="select2" onchange="showColumn(this.value);">
  <optgroup label="Table">

<?php
$table_count = mysql_query("SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = 'cl49-vclients'"); 

    $tables = array();
    while($row = mysql_fetch_array($table_count))
    {
?>
  <option value="<?php echo $row["TABLE_NAME"]; ?>"><?php echo $row["TABLE_NAME"]; ?></option>
<?php
   }
?>
  </optgroup>
</select>

The first select seems to be showing the table names fine, however when I select one another select field should appear but it doesnt, can anyone help?

  • 写回答

2条回答 默认 最新

  • duanmei1922 2015-05-05 11:17
    关注

    In the second query you are not selecting any database. You need

    mysqli_select_db($con,"information_schema");
    
    SHOW COLUMNS FROM '".$_POST['tablename']."'
    

    Alternatively, Replace your 2nd query like this

    SELECT COLUMN_NAME FROM information_schema.columns 
    WHERE table_schema = 'cl49-vclients' AND TABLE_NAME = '".$_POST['tablename']."';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计