如何在所有PHP页面中统一定义$db数据库连接变量?
generate.php and show.php Great question! Duplicating database connection logic across multiple files is a common pain point—let's clean this up by centralizing the connection into a single reusable file, so you only write that code once.
Here's the step-by-step solution:
Create a centralized database connection file
Make a new file nameddb-connect.php(you can use any name that fits your project structure) and move all the duplicate connection code into it:// db-connect.php // Connect to the database server and select database. $db = createDatabaseConnection($db_type, $db_host, $db_user, $db_pass, $db_name, $table_prefix); if (!$db instanceof KEYDatabase) { die(get_lang('no_db_connection')); }Update
show.phpto use the centralized connection
Remove the duplicate connection code fromshow.phpand include the shared connection file at the top:// show.php // Include the shared database connection require_once 'db-connect.php'; $result = $db->Show_keys(); foreach ($result as $row) { echo $row['key_value'] . "<br>"; }Update
generate.phpthe same way
Strip out the duplicate connection code fromgenerate.phpand include the shared file:// generate.php // Include the shared database connection require_once 'db-connect.php'; $key_value = serialkey(); $key_balance = 10; $key_created_date = date("Y-m-d h:m:s"); if ($db->addkey($key_value, $key_balance, $key_created_date)) { echo 'New Key added to database!<br>' . $key_value; }
Bonus: Centralize your configuration variables too
If your $db_type, $db_host, $db_user, etc., are also duplicated across files, you can take this a step further by moving those into a separate config.php file:
// config.php $db_type = 'your_database_type'; $db_host = 'your_host_address'; $db_user = 'your_db_username'; $db_pass = 'your_db_password'; $db_name = 'your_database_name'; $table_prefix = 'your_table_prefix';
Then update db-connect.php to include this config file first:
// db-connect.php require_once 'config.php'; $db = createDatabaseConnection($db_type, $db_host, $db_user, $db_pass, $db_name, $table_prefix); if (!$db instanceof KEYDatabase) { die(get_lang('no_db_connection')); }
Why this works:
require_onceensures the connection file is only loaded once, even if you accidentally include it multiple times (preventing duplicate connection attempts).- It eliminates code duplication entirely—any future changes to your database connection logic only need to be made in one place.
- It keeps your
show.phpandgenerate.phpfocused on their specific tasks, rather than handling connection boilerplate.
内容的提问来源于stack exchange,提问作者Amin Hijaz

