I am using PHP to design an interactive website. First, I designed three dropdown lists.
Say if a user picks a, b, c for each list. Then, I need to withdraw data from a database called S.
I want it first draw *table a** from database S and then the columns b and c from that table a.
I set q1, q2, and q3 as the value for the user picks in the dropdown list, but have no idea how to use them in the next step. Thanks for your help in advance!
Below is my code. I want to open Month column (q) in the Age Table.
$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>';
First give your dropdowns meaningfull names, like table
, column1
and column2
.
You can assign the actual table- and columnnames as values to the dropdownlists. But using numbers might be a bit safer because then nobody can see the tablesnames. Something like:
<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>
Put it in a form and POST to PHP. Now you can quite easily create a query.
<?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'