php:从数据库中提取表,并根据下拉列表从该表中提取列

mcvgt66p  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(379)

我正在使用php设计一个交互式网站。首先,我设计了三个下拉列表。
假设用户为每个列表选择a、b、c。然后,我需要从一个名为s的数据库中提取数据。
我要它首先从数据库s中画出表a,然后从表a中画出列b和c。
我将q1、q2和q3设置为用户在下拉列表中选择的值,但不知道如何在下一步中使用它们。提前谢谢你的帮助!
下面是我的代码。我想在age表中打开month列(q)。

$q = 'Month';
$sql = 'SELECT "$q" FROM Age';
$query = mysqli_query($conn, $sql);
if (!$query) {
    die ('SQL Error: ' . mysqli_error($conn));
    }
echo '<table><thead><tr><th>".$q."</th></tr></thead><tbody>';
while ($row = mysqli_fetch_array($query)){
    echo '<tr> <td>'.$row["$q"].'</td> </tr>';
    }
 echo '</tbody> </table>';
3qpi33ja

3qpi33ja1#

首先给出你的下拉列表的全名,比如 table , column1 以及 column2 .
可以将实际的表名和列名作为值分配给dropdownlists。但是使用数字可能更安全一些,因为这样就没有人能看到表名了。比如:

<select name="table">
   <option value="1">Age</option>
   <option value="2">Gender</option>
 </select>
<select name="column1">
   <option value="1">Week</option>
   <option value="2">Month</option>
   <option value="3">Year</option>
 </select>

把它放到一个表单中,然后发布到php。现在您可以很容易地创建一个查询了。

<?php 
//some sanitation: test if the POST-value has anything else then numbers in it.
if( $_POST['table'] != preg_replace('/[^0-9]/', '', $_POST['table']) die;
if( $_POST['column1'] != preg_replace('/[^0-9]/', '', $_POST['column1']) die;
if( $_POST['column2'] != preg_replace('/[^0-9]/', '', $_POST['column2']) die;

//create an array with the tablesnames
$my_tables=array(
    1=>'table_age',
    2=>'table_gender'
    );
//create an array with the column names that can be selected
$columns_per_table=array(
    //table_age
    1=>array(
      1=>'column_week',
      2=>'column_month',
      3=>'column_year'
      ),
    //table_gender
    2=>array(
      1=>'column_male',
      2=>'column_female',
      3=>'column_other'
      )
  );

//create a query with the POST values    
$table = $my_tables[ $_POST['table'] ];
$column1 = $columns_per_table[ $_POST['table'] ][ $_POST['column1'] ];
$column2 = $columns_per_table[ $_POST['table'] ][ $_POST['column2'] ];

$q='SELECT '.$column1.','.$column2.' FROM '.$table;
// example: $q='SELECT column_month,column_year FROM table_age'

相关问题