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

DDD
發布: 2024-10-26 06:13:31
原創
372 人瀏覽過

How to Store File Names and Form Data in a Database While Uploading Images with PHP?

上傳圖片時將檔案名稱存入資料庫

問題:

一個如何儲存如何儲存使用PHP 將圖像上傳到伺服器時,資料庫中的檔案名稱和其他表單資料?

解決方案:

1.表單結構:

使用下列HTML 程式碼建立一個擷取所需資訊的表單>

<code class="html"><form method="post" action="addMember.php" enctype="multipart/form-data">
  <p>Band Member Name:</p>
  <input type="text" name="nameMember">
  <p>Member's Position:</p>
  <input type="text" name="bandMember">
  <p>Photo:</p>
  <input type="hidden" name="size" value="350000">
  <input type="file" name="photo">
  <p>Other Information:</p>
  <textarea rows="10" cols="35" name="aboutMember"></textarea>
  <p>Other Bands:</p>
  <input type="text" name="otherBands" size=30>
  <input type="submit" name="upload" value="Add Member">
</form></code>
登入後複製
使用下列HTML 程式碼建立一個擷取所需資訊的表單:

2.伺服器端程式碼:

<code class="php">// Database connection and selection
$conn = mysqli_connect("host", "username", "password", "database");
if (!$conn) {
  die("Database connection failed: " . mysqli_connect_error());
}

// Form data extraction
$name = $_POST['nameMember'];
$bandMember = $_POST['bandMember'];
$photo = $_FILES['photo']['name'];
$about = $_POST['aboutMember'];
$bands = $_POST['otherBands'];

// Photo upload target directory
$target = "directory/";
$target .= basename($photo);

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

// Check for successful insertion
if ($result) {
  // If successful, move the uploaded photo to the server
  if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
    echo "File uploaded and data saved successfully.";
  } else {
    echo "Error uploading file.";
  }
} else {
  echo "Error saving data.";
}
mysqli_close($conn);</code>
登入後複製
使用下列PHP 腳本處理表單資料:

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

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!