上传图像时将文件名存储在数据库中
挑战:
将图像上传到服务器并将其文件名存储在数据库中,同时捕获其他表单数据构成了常见的挑战网络开发人员。
解决方案:
1.表单修改:
用于图片上传和数据收集的表单应包括:
<form method="post" action="addMember.php" enctype="multipart/form-data"> <!-- ... Additional form fields here ... --> <input type="hidden" name="size" value="350000"> <label for="photo">Photo:</label> <input type="file" name="photo"> <!-- ... Additional form fields here ... --> </form>
2.用于处理的 PHP 代码:
PHP 代码处理表单数据并将图像上传到服务器:
<?php // Connect to database $connection = mysqli_connect("yourhost", "username", "password", "dbname"); // Retrieve form data $name = $_POST['nameMember']; $bandMember = $_POST['bandMember']; $pic = $_FILES['photo']['name']; $about = $_POST['aboutMember']; $bands = $_POST['otherBands']; // Upload image if (move_uploaded_file($_FILES['photo']['tmp_name'], "your-upload-path/$pic")) { // Insert data into database $query = "INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands) VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')"; $result = mysqli_query($connection, $query); // Check if data was inserted successfully if ($result) { echo "Data and image uploaded successfully"; } else { echo "Error uploading data or image: " . mysqli_error($connection); } } else { echo "Error uploading image"; } // Close database connection mysqli_close($connection); ?>
以上是如何在上传过程中高效地将图像文件名存储在数据库中?的详细内容。更多信息请关注PHP中文网其他相关文章!