首頁  >  文章  >  後端開發  >  如何使用 PHP 上傳時將圖像檔案名稱和其他表單資料儲存在資料庫中?

如何使用 PHP 上傳時將圖像檔案名稱和其他表單資料儲存在資料庫中?

Patricia Arquette
Patricia Arquette原創
2024-10-26 06:20:02918瀏覽

How to Store Image File Names and Other Form Data in a Database During Uploads with PHP?

使用PHP 將圖像上傳到服務器時如何存儲文件名和其他信息

問題:

將圖像上傳到伺服器時,如何確保檔案名稱與其他表單資料一起儲存在資料庫中?

答案:

要在使用PHP 將圖像上傳到伺服器時存儲表單中的文件名和附加信息,請按照以下步驟操作:

表單:

建立包含檔案上傳欄位和您要儲存的其他資料的表單。

PHP 腳本:

  1. 連接到您的資料庫。
  2. 從表單中獲取信息,包括文件名。
  3. 將資訊插入資料庫表中,包括檔案名稱。
  4. 使用 move_uploaded_file() 函數移動上傳的圖片到達其預定目的地。

這是一個範例腳本:

<code class="php">// Database connection details
$host = 'localhost';
$user = 'username';
$password = 'password';
$database = 'database_name';

// Connect to the database
$conn = mysqli_connect($host, $user, $password, $database);

// Get the form data, including the File
$name = $_POST['nameMember'];
$position = $_POST['bandMember'];
$photo = $_FILES['photo']['name'];
$about = $_POST['aboutMember'];
$otherBands = $_POST['otherBands'];

// Insert data into the database
$sql = "INSERT INTO tableName (nameMember, bandMember, photo, aboutMember, otherBands) VALUES ('$name', '$position', '$photo', '$about', '$otherBands')";

if ($conn->query($sql) === TRUE) {
    // Upload the file to the server
    $target = "your directory" . $photo;
    if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
        echo "The file $photo has been uploaded, and your information has been added to the database.";
    } else {
        echo "Sorry, there was a problem uploading your file.";
    }
} else {
    echo "Error: " . $conn->error;
}

// Close the database connection
$conn->close();</code>

以上是如何使用 PHP 上傳時將圖像檔案名稱和其他表單資料儲存在資料庫中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn