How to Load Data from Database into Custom Files (v2025)

Starting v2025, I decided not to disable Include common files option in order to get data from database into a Custom File. This is important, since v2025, PHPMaker strict to recommend us to always enable that option in order to use some built-in global functions.

So, if you want to load data from database into a Custom File in v2025, you may try the following.

  1. From demo2025 project, create a new Custom File, name it with test.php, and make sure you always enable Include common files option
  2. Copy the following code into Content section of that Custom File:
<?php

echo "<h3>Custom File with Include common files option</h3>";

$sql = "SELECT `Model` FROM `models`"; // define your SQL
$stmt = ExecuteQuery($sql); // execute the query
$value = ""; // initial value
if ($stmt->rowCount() > 0) { // check condition: if record count is greater than 0
    while ($row = $stmt->fetchAssociative()) { // loop
        $value .= $row["Model"] . "<br>"; // in case the result returns more than one record, display it and separated by line break
    } // end loop
    echo "Here is the Models list: <br>" . $value; // display the result
} else { // if there are no result
    echo "No record found."; // display the message
} // end of check condition


?>

If you only login the user and do something without any HTML in response, you better use Route_Action server event.

1 Like

Well, although it is strongly not recommended to disable Include common files option for Custom File if you want to get data from database into a Custom File, however, as matter of fact, PHPMaker v2025 has still the ability to allow us to disable that option, after I reading this following post: What is the equiv. of loading system libraries? - #7 by yaaryvp

So, if you want to obviously to disable that option (again, it is strongly not recommended), here is the code to get data from database into a Custom File with disabling the Include common files option for v2025:

<?php
namespace PHPMaker2025\demo2025;

use DI\ContainerBuilder;

// Autoload
require_once "vendor/autoload.php";

// Require files
require_once "src/constants.php";
require_once "src/config.php";
require_once "src/phpfn.php";
require_once "src/userfn.php";

$containerBuilder = new ContainerBuilder();
$containerBuilder->useAttributes(true);

// Add definitions
$containerBuilder->addDefinitions("src/definitions.php");

// Dispatch container build event
DispatchEvent(new ContainerBuildEvent($containerBuilder), ContainerBuildEvent::NAME);

// Build PHP-DI container instance
$container = $containerBuilder->build();

echo "<h3>Custom File without Include common files option</h3>";

$sql = "SELECT `Model` FROM `models`"; // define your SQL
$stmt = ExecuteQuery($sql); // execute the query
$value = ""; // initial value
if ($stmt->rowCount() > 0) { // check condition: if record count is greater than 0
    while ($row = $stmt->fetchAssociative()) { // loop
        $value .= $row["Model"] . "<br>"; // in case the result returns more than one record, display it and separated by line break
    } // end loop
    echo "Here is the Models list: <br>" . $value; // display the result
} else { // if there are no result
    echo "No record found."; // display the message
} // end of check condition

?>
1 Like

If you want to get/extract the database configuration setting in that Custom File, you may simply use:

var_dump(Config("Databases"));
2 Likes

If you want to get/extract the connection info from your Database_Connecting server event (if any), then you may simply put this following code into your Global Code server event:

AddListener(DatabaseConnectingEvent::NAME, function(DatabaseConnectingEvent $event) {
    // $option = $event["my_option"]; // Get an option
	global $CurrentPageID;
	if ($CurrentPageID == "test.php")
		var_dump($event);
});

and then make sure also you put this following code into your Custom File (without Include common function option enabled):

global $CurrentPageID;
$CurrentPageID = "test.php"; // assume your custom file name is "test.php"

before this line:

echo "<h3>Custom File without Include common files option</h3>";
1 Like

we updated our 2024 custom files with your 2025 code, but seems

any calls to WriteAuditTrail() fail.

does something need to be initialized in order to utilize the audit trail?

here’s an excerpt

<?php
namespace PHPMaker2025\dams;

use DI\ContainerBuilder;

// Autoload
require_once "../vendor/autoload.php";

// Require files
require_once "../src/constants.php";
require_once "../src/config.php";
require_once "../src/phpfn.php";
require_once "../src/userfn.php";

$containerBuilder = new ContainerBuilder();
$containerBuilder->useAttributes(true);

// Add definitions
$containerBuilder->addDefinitions("../src/definitions.php");

// Dispatch container build event
DispatchEvent(new ContainerBuildEvent($containerBuilder), ContainerBuildEvent::NAME);

// Build PHP-DI container instance
$container = $containerBuilder->build();
?>

<?php
    if(php_sapi_name() != "cli") {
        die();
    }
            
    date_default_timezone_set('America/New_York');           
    $conn = Conn();

    WriteAuditTrail("log", CurrentDateTime(), "", "Generate Expiring Events", "START", "", "", "", "", "INITIALING");
#15 phpfn.php(275): DI\Container->get('audittrail')
#16 phpfn.php(2819): PHPMaker2025\dams\Container('audittrail')
#17 d_campaign_generate_campaign_expiring_messages.php(42): WriteAuditTrail('log', '2025-01-17 12:3...', '', 'Generate Campai...', 'START', '', '', '', '', 'INITIALING')
#18 {main}
  thrown in phpfn.php on line 226

line 226 in phpfn.php

/**
 * Get request object
 *
 * @return Request
 */
function Request(): Request
{
    return $GLOBALS["Request"];
}

I assume you are using Custom File with Include common files option disabled, and you want to save it into audittrail table in database.

If so, then you cannot use WriteAuditTrail global function, and this is one of another limitation if you disable Include common files option for the Custom File.

So, the solution is, you may simply use this following code in your Custom File:

$row = ["datetime" => CurrentDateTime(),
        "script" => "",
        "user" => "",
        "ew-action" => "Executing test.php",
        "table" => "",
        "field" => "",
        "keyvalue" => "start",
        "oldvalue" => "",
        "newvalue" => "completed"
        ];
$logger = Container("app.audit");
$logger->info(__FUNCTION__, $row);

You may check the output of the audit from the generated log folder (assume you setup log/ under PHPGeneral OptionsLoggingLog files folder) of your web application.

finally upgraded to 2025 and need to look at this now…

implemented, works writing to log file, can it write to the DB as we use a table for our logging ?

Yes, if only you enable Include common files option for your Custom File. If not, then the audit trail only supports to log file, not to database. Please CMIIW.

Another tips that related to Custom Files with Include common files option disabled is, sometimes you want to get the current language ID by using CurrentLanguageID() global function.

To achieve this, then you have to create Container for app.language as follows:

$lang = Container("app.language");
echo "<br>CurrentLanguageID(): " . CurrentLanguageID();
echo "<br>LanguageID: " . $lang->LanguageId;

This doesn’t appear to work any longer in 2025, it throws an error attempting to create the container

I cannot reproduce the issue. Mine is still working properly here.

You should always post your complete code in that Custom File for discussion, so others could try/reproduce the issue.

It is recommended NOT to use this approach anymore, you may want to read Using Route_Action server event (v2021). If you prefer custom file, you may add your own controller.

DO NOT use standalone custom file anymore, you can use the new Controller_Action Server Event or use the Route/API Action Controllers of v2026.

What would be the v2026 version of this code?

And what would be the code template for a CLI script?

any update on the code for v2026?

many thanks

Short answer

It is recommended NOT to use this approach anymore.

For v2026, read Migrating to v2026 -> Route/API Action Server Events Replaced by Route/API Action Controllers.

Long Answer

v2026 uses Symfony, it follows a strict modern architecture. Manually including files is now essentially trying to run code outside of the framework's "brain."

Here is why you should avoid that old approach:

  • The Kernel isn't Booted: Symfony uses a Service Container to manage everything (database, security, sessions). If you just include files manually, the "Kernel" doesn't boot. This means global functions won't work because their services aren't "awake."
  • Broken Security: PHPMaker/Symfony’s security only protects routes it knows about. By using a standalone file, you bypass the framework's gatekeeper, making it much harder to safely verify if a user is logged in or has the right permissions.
  • Audit & Logging Issues: Advanced features like Audit Trails rely on the framework being fully initialized to write to your database. Without the proper Symfony context, these features either break or default to basic text logs.
  • Path Fragility: PHPMaker/Symfony projects have a specific directory structure. Hardcoding paths to src/ or vendor/ is a maintenance nightmare; if the framework updates or moves a file, your custom script will immediately break.

The better way: Use Controller_Action Server Event or Route/API acton controllers. This registers your code as a proper route. The framework boots up completely, giving you full, safe access to every feature automatically.