You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP头像上传至网站但文件名未存入数据库,求代码问题排查

Troubleshooting Why Your Image Filename Isn't Saving to the Database

Let's walk through the issues in your code and fix them one by one:

1. Undefined $con_id breaks your UPDATE query

In the first code block, you set $_SESSION['id'] = "$con_id"; but $con_id is never defined anywhere. That means $_SESSION['id'] ends up empty (or set to a meaningless value), so your UPDATE query can't find any user matching WHERE id = ''—no wonder the filename never gets saved to the database.

You need to set $_SESSION['id'] to the actual logged-in user's ID. For example, after authenticating a user during login, you should have something like:

// Example: After validating user credentials
$_SESSION['id'] = $user_id_from_database; // Replace with your actual user ID variable

2. Redundant database connections

You're connecting to the database twice (with mysqli_connect in both code blocks) which is unnecessary and can cause unexpected behavior. Reuse a single connection instead of creating multiple ones.

3. Missing error checking

You don't verify if the file upload succeeded or if the SQL query ran without issues. Adding these checks will help you debug exactly where things are going wrong.

4. Critical SQL injection risk

Directly inserting $_FILES['file']['name'] and $_SESSION['id'] into your SQL query is a major security hole. Always use prepared statements to sanitize user input.


Fixed Code Example

Here's a revised version of your code that addresses all these problems:

<?php
session_start();

// Single database connection with error checking
$con = mysqli_connect("my host", "my account", "my password", "my table name");
if (!$con) {
    die("Database connection failed: " . mysqli_connect_error());
}

// Ensure user is logged in with a valid session ID
if (!isset($_SESSION['id'])) {
    die("Error: User is not logged in.");
}

if (isset($_POST['submit'])) {
    // Check if file uploaded without errors
    if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $targetDirectory = "../userstorage/p_photos/";
        $fileName = basename($_FILES['file']['name']); // Sanitize filename to prevent path attacks
        $targetFilePath = $targetDirectory . $fileName;

        // Move uploaded file to target directory
        if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath)) {
            // Use prepared statement to safely update database
            $stmt = mysqli_prepare($con, "UPDATE users SET image = ? WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "si", $fileName, $_SESSION['id']);
            
            if (mysqli_stmt_execute($stmt)) {
                echo "Success! File uploaded and filename saved to database.";
            } else {
                echo "Failed to save filename to database: " . mysqli_error($con);
            }
            mysqli_stmt_close($stmt);
        } else {
            echo "Failed to move uploaded file to storage directory.";
        }
    } else {
        echo "File upload error occurred: Error code " . $_FILES['file']['error'];
    }
}
?>

Key Improvements:

  • Added database connection error handling to catch connection issues early
  • Verified the user's session ID exists before attempting database updates
  • Checked for file upload errors to ensure the file was uploaded correctly
  • Used prepared statements to eliminate SQL injection risks
  • Added clear success/error messages to help with debugging
  • Sanitized the filename with basename() to prevent path traversal attacks

内容的提问来源于stack exchange,提问作者Adel Store

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:38:02