基于登录用户创建数据库驱动用户资料时查询出错求助
Hey there! Let's troubleshoot this issue step by step—since you're trying to query data based on a logged-in user but hitting errors, we'll start with the most common culprits first:
First, make sure your user's login state is actually being stored and retained across pages:
- Confirm both
login.phpandhomepageDemo.phpstart withsession_start();at the very top (before any HTML output)—without this, session variables won’t work. - Verify that after successful login in
login.php, you’re setting a session variable for the user’s unique ID, like:// After validating username/password $_SESSION['user_id'] = $user_record['id']; // Replace 'id' with your users table's primary key name - Test if the session variable exists in
homepageDemo.phpby adding a debug line:var_dump(isset($_SESSION['user_id'])); // Should return bool(true) if logged in
Let’s make sure your login logic is actually working as intended:
- Ensure your function correctly fetches the user record from the database and validates credentials (never compare passwords directly—use
password_verify()for hashed passwords!). - Check if the function handles database errors properly. For example, with MySQLi:
function validateUser($username, $password) { global $db_conn; $stmt = $db_conn->prepare("SELECT id, password FROM users WHERE username = ?"); $stmt->bind_param("s", $username); $stmt->execute(); $result = $stmt->get_result(); // Catch query errors if ($stmt->error) { error_log("Login query error: " . $stmt->error); return false; } if ($result->num_rows === 0) { return false; // User not found } $user = $result->fetch_assoc(); if (password_verify($password, $user['password'])) { $_SESSION['user_id'] = $user['id']; // Critical: Set session here return true; } return false; } - Make sure no code after the login success is overwriting or unsetting
$_SESSION['user_id'].
Most errors here come from misusing session variables or invalid SQL syntax:
- Always use prepared statements to avoid SQL injection and syntax errors. Example of a valid user-specific query:
if (!isset($_SESSION['user_id'])) { header("Location: accounts/login.php"); exit; // Redirect unlogged users } $stmt = $db_conn->prepare("SELECT * FROM your_target_table WHERE user_id = ?"); $stmt->bind_param("i", $_SESSION['user_id']); // Use "s" if user_id is a string $stmt->execute(); $user_data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC); // Check for query errors if ($stmt->error) { echo "Query Error: " . $stmt->error; exit; } - Verify that the column name in your WHERE clause matches your database schema (e.g., if your table uses
user_idinstead ofuserid, don’t mix them up).
Ensure your tables are set up to support user-specific queries:
- Your
userstable must have a unique primary key (e.g.,id INT AUTO_INCREMENT PRIMARY KEY). - The table you’re querying (e.g.,
orders,user_profiles) must have a foreign key column that references the users table’s primary key (e.g.,user_id INT NOT NULLwith a foreign key constraint pointing tousers.id). - Confirm data types match: If
users.idis an integer,user_idin your target table should also be an integer (no mismatches like string vs int).
The most helpful step is to get the specific error text. Add error logging or output to your code:
- For MySQLi: Use
$stmt->errorormysqli_error($db_conn)to get SQL errors. - For PHP session/undefined variable errors: Check your server’s error log, or enable display_errors temporarily (only in development!):
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
Once you have the exact error message, it’ll be much easier to pinpoint the issue—whether it’s a missing session variable, a typo in your SQL, or a database schema mismatch.
内容的提问来源于stack exchange,提问作者user9445468

