上傳圖片並在資料庫中儲存檔案名稱
將圖片上傳到伺服器時,通常需要將檔案名稱與資料庫中的其他資訊.這樣可以輕鬆檢索和管理上傳的文件。此問題旨在解決此要求並提供詳細的解決方案。
提供的表單允許用戶上傳照片並輸入有關樂隊成員的各種詳細信息,例如他們的姓名、職位、傳記以及他們所參加的其他樂隊為了處理數據並將其存儲到數據庫中,使用以下程式碼:
<?php // Connect to the database $mysqli = new mysqli("yourhost", "username", "password", "dbName"); if ($mysqli->connect_error) { die("Connection to database failed: " . $mysqli->connect_error); } // Prepare the data from the form $name = $_POST['nameMember']; $bandMember = $_POST['bandMember']; $photo = $_FILES['photo']['name']; $about = $_POST['aboutMember']; $bands = $_POST['otherBands']; // Prepare the SQL statement $sql = "INSERT INTO tableName (nameMember, bandMember, photo, aboutMember, otherBands) VALUES (?, ?, ?, ?, ?)"; // Bind the parameters to the SQL statement $stmt = $mysqli->prepare($sql); $stmt->bind_param("sssss", $name, $bandMember, $photo, $about, $bands); // Execute the SQL statement $stmt->execute(); // Check if the photo was uploaded successfully if (move_uploaded_file($_FILES['photo']['tmp_name'], "your directory/" . $photo)) { echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the database"; } else { echo "Sorry, there was a problem uploading your file."; } // Close the database connection $stmt->close(); $mysqli->close(); ?>
此程式碼首先連接到資料庫,準備資料和SQL 語句,綁定將參數傳遞給SQL語句,執行該語句,最後檢查照片是否已上傳成功。如果上傳成功,則會列印成功訊息。否則,它會列印一條錯誤訊息。
透過實作此解決方案,您可以成功將映像上傳到伺服器並將其名稱和其他相關資訊儲存在資料庫中。
以上是如何上傳圖片並在資料庫中儲存檔案名稱?的詳細內容。更多資訊請關注PHP中文網其他相關文章!