使用 PHP 将图像上传到服务器时如何存储文件名和其他信息
问题:
将图像上传到服务器时,如何确保文件名与其他表单数据一起存储在数据库中?
答案:
要在使用 PHP 将图像上传到服务器时存储表单中的文件名和附加信息,请按照以下步骤操作:
表单:
创建包含文件上传字段和您要存储的其他数据的表单。
PHP 脚本:
这是一个示例脚本:
<code class="php">// Database connection details $host = 'localhost'; $user = 'username'; $password = 'password'; $database = 'database_name'; // Connect to the database $conn = mysqli_connect($host, $user, $password, $database); // Get the form data, including the File $name = $_POST['nameMember']; $position = $_POST['bandMember']; $photo = $_FILES['photo']['name']; $about = $_POST['aboutMember']; $otherBands = $_POST['otherBands']; // Insert data into the database $sql = "INSERT INTO tableName (nameMember, bandMember, photo, aboutMember, otherBands) VALUES ('$name', '$position', '$photo', '$about', '$otherBands')"; if ($conn->query($sql) === TRUE) { // Upload the file to the server $target = "your directory" . $photo; if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { echo "The file $photo has been uploaded, and your information has been added to the database."; } else { echo "Sorry, there was a problem uploading your file."; } } else { echo "Error: " . $conn->error; } // Close the database connection $conn->close();</code>
以上是如何使用 PHP 上传时将图像文件名和其他表单数据存储在数据库中?的详细内容。更多信息请关注PHP中文网其他相关文章!