上传图片时将文件名存入数据库
问题:
一个存储如何使用 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>
2.服务器端代码:
使用以下 PHP 脚本处理表单数据:
<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中文网其他相关文章!