将MySQL表存入变量后,换代码连接正常但$account、$player无DB分配求助
Hey there, let's work through this problem together—you've already fixed the connection error, so we're halfway there! Here's how to tackle the missing database assignment for $account and $player:
1. Verify You're Passing the Connection to Your Variables
First, double-check how $account and $player are being set up. If these are instances of classes (like account/player models), you need to make sure you're passing your active database connection when you instantiate them. For example:
- If you're using MySQLi:
// After confirming $conn is a valid connection $account = new Account($conn); $player = new Player($conn); - If you're using PDO:
$account = new Account($pdoConn); $player = new Player($pdoConn);
If you skipped passing the connection object, those variables won't have access to the database—this is the most common culprit here.
2. Debug the Connection Object's Validity
Even if you don't get a "connection failed" error, it's worth confirming your connection is actually functional. Add quick debug lines right after establishing the connection:
- For MySQLi:
var_dump($conn); // Should show a mysqli object, not null/false if ($conn->connect_error) { die("Hidden connection error: " . $conn->connect_error); } - For PDO:
var_dump($pdoConn); // Should show a PDO object $pdoConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Force errors to show up
This will catch any silent connection issues that might be preventing your variables from linking to the DB.
3. Check for Variable Scope Problems
If $account and $player are defined inside a function (like a setup function), they might not be accessible in the rest of your code. For example:
function setupDB() { $conn = mysqli_connect("host", "user", "pass", "db"); $account = new Account($conn); // Only exists inside this function }
Fix this by either returning the variables from the function, using the global keyword (use sparingly!), or passing them by reference. A cleaner approach is returning:
function setupDB() { $conn = mysqli_connect("host", "user", "pass", "db"); return [ 'account' => new Account($conn), 'player' => new Player($conn) ]; } // Then in your main code: $dbObjects = setupDB(); $account = $dbObjects['account']; $player = $dbObjects['player'];
4. Compare Old vs. New Code for Missing Logic
Go back to your original code (the one that had connection errors but assigned $account/$player correctly). Look for lines where the database connection was linked to those variables—maybe something like:
$account->dbConnection = $oldConn; $player->setDB($oldConn);
Make sure you replicate that logic in your new working connection code. It's easy to fix the connection and forget to reattach those links!
内容的提问来源于stack exchange,提问作者Octavian Niculescu

