上傳圖片時將檔案名稱存入資料庫
問題:
一個如何儲存如何儲存使用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中文網其他相關文章!