Database Connection in External File

Dear Team,

When I create an external PHP file, I’m not sure how to properly use the program’s database connection. Currently, I establish the connection manually as follows:

php

CopyEdit

$conn = new PDO("mysql:host=localhost;dbname=order_management", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

However, when I upload the project to the server, I have to manually adjust the connection parameters based on the hosting environment.

Is there a recommended way to use the existing database connection from the main application in external files? Any guidance or assistance on this matter would be greatly appreciated.

Best regards,

please can you explain with example?

  1. Don’t use external file any more, see above topic.
  2. In your Route_Action or controller (by Custom File), you can use the global functions, e.g. Conn(), so you can connect easily. The docs has description and examples. If you use the main database connection in your project, it is simply:
$conn = Conn();

Note the connection is a DBAL connection, not a PDO connection.

1 Like