Skip to content
Advertisement

How to select table on DB using a dropdown?

Let’s say that I have two tables on my DB (table1 and table2, and both of them have the same structure.

  Column   |  Type   | Collation | Nullable | Default | Storage  | Stats target | Description
-----------+---------+-----------+----------+---------+----------+--------------+-------------
 name      | text    |           |          |         | extended |              |
 days_week | text    |           |          |         | extended |              |
 datetime  | tsrange |           |          |         | extended |              |
 room      | text    |           |          |         | extended |              |
 semester  |text     |           |          |         |extended. |              |

Indexes:
“table1_name_days_week_datetime_excel” EXCLUDE USING gist (name with=, days_week with=, date time with &&)
"table1_room_days_week_datetime_excel” EXCLUDE USING gist (room with=, days_week with=, datetime with &&)

My goal is to insert the data on the table that I’ll be deleting on the dropdown.

Sample if I select 1° semester on the dropdown all of the data will be added on the table1.

if I select 2° semester on the dropdown all of the data will be added on the table2.

This is what I have so far

<form name="testform" method='POST' action="add.php">
<label>Semester</label>
<select type="text" name=semester>
<option value=1ºsemester>1º semester</option>
<option value=2ºsemester>2º semester</option>
</select>
<input type=submit value=Registrar>
</form>

<?php

$semester=$_POST['semester'];

$con = @pg_connect ("port=5432 host=localhost dbname=postgres user=postgres password=a");

if($con == NULL) {
echo "Cannot Connect to database.";
exit (0);
}

$sql = "insert into ? (name, days_week, datetime, room, semester) values ('$name', '$days_week', '$datetime', '$room', '$semester');";
$res = @pg_query ($con, $sql);
if ($res == NULL){
echo "Error";

exit (0);
} 
?>

Thanks in advance for any help

Advertisement

Answer

Just add a check before executing the query.

$semester=$_POST['semester'];
if($semester == '1ºsemester'){
  $table = "table_1";
}else{
  $table = "table_2";
}

$q = "insert into $table ........";
//Rest of your code 
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement