简体   繁体   中英

How to dynamically select a table from mysql using PHP

I created an html that has a formulary that let you choose between four different options:

<select name="especie">
  <option value = "1"> Hyundai </option>
  <option value = "2"> Renault </option>
  <option value = "3"> Ford </option>
  <option value = "4"> Fiat </option>
</select>

Each of these options correspond to one table in a mySQL database (let´s say it´s called companies), and have the same variables. The html then lets you perform the query, and I want it to display the information according to the table you have previously chosen.

$query = "SELECT * FROM $table WHERE brand LIKE ´%$brand%´;";

So what I want is to create a PHP that chooses dynamically the table ($table) depending on the chosen option by the user (in the first chuck of code).

Any help would be really appreciated it.

Without re designing your DB structure - which could be the best course of action, there are two easy ways to do this. You could do it basically the way you said. If choosing this method you need to make sure that the table is being selected by a key from an array of tables so it is a safe input like so:

$tables = ["table1" => "table1","table2" =>"table2"];
$query = "SELECT * FROM ".$tables[$table_key_from_input]." WHERE brand LIKE ´%$brand%´;";

But this is not ideal as, when tables are added removed all code like this needs to be updated.

Another way of getting the desired outcome would be to make a database view which is a union of all the tables (plus the table name in an extra column) then you can just select from the view every time using the table as a variable supplied by the user input.

You can learn about views here: https://www.w3schools.com/sql/sql_view.asp

And see how to make a union here: https://www.w3schools.com/sql/sql_union.asp

The view code would look a little like this:

CREATE VIEW view_name AS
SELECT *, 'table1' AS 'table' FROM table1
UNION
SELECT *, 'table2' AS 'table' FROM table2

Then your query would be like this:

$query = "SELECT * FROM view_name WHERE brand LIKE ´%$brand%´ AND table = $table;"; 

(But ideally using PDO!)

Also if you do it this way if you ever re think your db structure and perhaps do what was suggested by El_Vanja in the comments you can, and by deleting the view and giving the table the same name the code wouldn't even have to change!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM