首頁  >  文章  >  後端開發  >  PHP上傳圖片時如何將檔案名稱儲存在資料庫中?

PHP上傳圖片時如何將檔案名稱儲存在資料庫中?

Patricia Arquette
Patricia Arquette原創
2024-10-29 02:39:30976瀏覽

How to Store File Names in a Database When Uploading Images in PHP?

使用PHP 將圖像上傳到伺服器時如何在資料庫中儲存檔案名稱

當您想要將圖片連結到其他資料時,需要將檔案名稱儲存在資料庫中您的申請。這使您可以輕鬆檢索和顯示與特定記錄關聯的影像。為此,您需要使用一些技術來處理文件上傳和資料庫插入。

讓我們從收集圖片和其他資訊的表單開始:

 ;<br>
<input type="text" name="nameMember" placeholder="Band Member Name"/>
<input type="text" name="bandMember" placeholder="Band Member Position"/>
<input type="file" name="photo" accept="image/*" />
<textarea name="aboutMember" placeholder="Additional Member Information"></textarea>
<input type="text" name="otherBands" placeholder="Other Bands Member Has Been In"/>
<input type="submit" name="upload" value="Add Member"/>


pre>

接下來,您將編寫PHP 腳本來處理表單資料並處理影像上傳:

<br><?php </p><p>$targetDirectory = "images/";<br>$targetFilePath = $targetDirectory .basename($_FILES'照片');</p><p><br>$nameMember = $_POST['nameMember'];<br>$bandMember = $_POST['bandMember'];<br>$aboutMember = $_POST[' aboutMember'];</p>$otherBands = $_POST[' otherBands'];<p></p>嘗試{<pre class="brush:php;toolbar:false">// Connect to the database
$conn = new PDO('mysql:host=localhost;dbname=yourdbname', 'username', 'password');

// Prepare the SQL statement to insert data into the database
$stmt = $conn->prepare("INSERT INTO members (name, band_position, photo, about, other_bands) 
VALUES (:name, :band_position, :photo, :about, :other_bands)");

// Bind the parameters to the SQL statement
$stmt->bindParam(':name', $nameMember);
$stmt->bindParam(':band_position', $bandMember);
$stmt->bindParam(':photo', $photoName);
$stmt->bindParam(':about', $aboutMember);
$stmt->bindParam(':other_bands', $otherBands);

// Execute the SQL statement
$stmt->execute();

// Upload the image to the server
if (move_uploaded_file($_FILES['photo']['tmp_name'], $targetFilePath)) {
    // Image uploaded successfully
    echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the database.";
} else {
    // Image upload failed
    echo "Sorry, there was a problem uploading your file.";
}

} catch (PDOException $e) {
echo "Error: " . $e->getMessage();

}


$conn = null;
?>

在此程式碼中,我們使用PDO 建立資料庫連線並準備SQL 語句將資料插入資料庫。我們也將表單資料綁定到 SQL 參數並執行語句。最後,我們將圖片上傳到指定目錄。

按照以下步驟,您可以成功將上傳的檔案名稱和其他資訊儲存到資料庫中。

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

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