Home » Php » php – Is it a good practice to automatically create tables in a database?

php – Is it a good practice to automatically create tables in a database?

Posted by: admin February 25, 2020 Leave a comment


Here’s the thing: I’m developing an online store. I have a model which is currently working very well.
The thing is that I want to add the “create branch option”, you know… To allow the user to have more branches and manage them all from the same website.
I have several tables; based on hierarchy, we could say that the tables: employees, customers and branches are on the same hierarchy; simply because it’s one single company so theres no need to be branch-dependant.
The problem comes along with the table branches, cause I have for example, the table “products” which has columns such as: ID, description, category… and the like.
I want each company to have its own inventory but I cannot just simply add the column “branch” to the table products because if each branch will have its own inventory, then the ID, which is a primary key, can’t be repeated. It means that I could only assign it to one branch but no other branch could have the same product in its inventory.
So I was thinking of creating a script to automatically create all of the tables that depend on branch (products, inventory, sales, payments, etc)
I’m using PHP. So I could detect the branch that is on use and since each branch has an ID I could just name the automatically-generated tables with the same name + the unique ID.
For example I’m watching the info of branch 2, with an ID of 2, let’s say. And that branch ID = 2 is stored in $_SESSION[“branchID”]. So in the case of selecting all of the products from. Branch 2,i would only need to do something like
$query = “select * from products”.$_SESSION[“branchID”];
My question is:
Is it a good practice to automatically generate these new tables?
PD. I know it may not be a good practice to concatenate, I’m using POO functions with mysqli,to avoid mysql injection. I would only concatenate this ID, which I would get from the database directly, so it means, users will never have access to it.
Could you suggest me what to do, please?

How to&Answers: