上传图片并在数据库中存储文件名
将图片上传到服务器时,通常需要将文件名与数据库中的其他信息。这样可以轻松检索和管理上传的文件。此问题旨在解决此要求并提供详细的解决方案。
提供的表单允许用户上传照片并输入有关乐队成员的各种详细信息,例如他们的姓名、职位、传记以及他们所参加的其他乐队为了处理数据并将其存储到数据库中,使用以下代码:
<?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中文网其他相关文章!