使用PHP 將圖像上傳到伺服器時如何在資料庫中儲存檔案名稱
當您想要將圖片連結到其他資料時,需要將檔案名稱儲存在資料庫中您的申請。這使您可以輕鬆檢索和顯示與特定記錄關聯的影像。為此,您需要使用一些技術來處理文件上傳和資料庫插入。
讓我們從收集圖片和其他資訊的表單開始:
;<br>
接下來,您將編寫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;
?>
以上是PHP上傳圖片時如何將檔案名稱儲存在資料庫中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!