This topic is locked

restAPI on multiple database

3/27/2025 2:45:57 AM
PHPRunner General questions
J
jacktonghk authorDevClub member

I have multi-tennant project in which I stored the database name stored in the user table. Upon user log on, the database connect wlill be changed to what is stored the user table. Now, I want to do the sane with restAPI v1.php, how can I change the database connection as it does with normal login? Thank you.

Jack Tong

Sergey Kornilov admin 3/27/2025

The correct approach is to switch to a correct database based on the API key passed via REST API request.

J
jacktonghk authorDevClub member 3/27/2025

Do I need to modify the v1.php or api.php?

Sergey Kornilov admin 3/28/2025

You should not be modifying any of the source files.

What event do you use to change the database connection on the fly?

J
jacktonghk authorDevClub member 4/1/2025

In my original project, I have my primary DB connection based on $_SESSION["dbname'] and then I set the $_SESSION["dbname"] variable in the 'after successful login' event. My users table for user login is located in my secondary DB connection which has fixed Database name.

Sergey Kornilov admin 4/1/2025

In the same code where you "I have my primary DB connection based on $_SESSION['dbname']" you need to perform the following:

  • check if you are in REST API mode now
  • read API key from GET or POST request
  • based on this API key $_SESSION["dbname'] to corresponding database name