首页 > 后端开发 > php教程 > PHP上传图片时如何将文件名存储在数据库中?

PHP上传图片时如何将文件名存储在数据库中?

Patricia Arquette
发布: 2024-10-29 02:39:30
原创
1018 人浏览过

How to Store File Names in a Database When Uploading Images in PHP?

使用 PHP 将图像上传到服务器时如何在数据库中存储文件名

当您想要将图像链接到其他数据时,需要将文件名存储在数据库中您的申请。这使您可以轻松检索和显示与特定记录关联的图像。为此,您需要使用一些技术来处理文件上传和数据库插入。

让我们从收集图像和其他信息的表单开始:

 ;<br><form method="post" action="addMember.php" enctype="multipart/form-data"><pre class="brush:php;toolbar:false"><input type="text" name="nameMember" placeholder="Band Member Name"/>
<input type="text" name="bandMember" placeholder="Band Member Position"/>
<input type="file" name="photo" accept="image/*" />
<textarea name="aboutMember" placeholder="Additional Member Information"></textarea>
<input type="text" name="otherBands" placeholder="Other Bands Member Has Been In"/>
<input type="submit" name="upload" value="Add Member"/>
登录后复制


pre>

接下来,您将编写 PHP 脚本来处理表单数据并处理图像上传:

<br><?php </p><p>$targetDirectory = "images/";<br>$targetFilePath = $targetDirectory . basename($_FILES'照片');</p><p>$nameMember = $_POST['nameMember'];<br>$bandMember = $_POST['bandMember'];<br>$aboutMember = $_POST[' aboutMember'];<br>$otherBands = $_POST['otherBands'];</p><p>尝试 {</p><pre class="brush:php;toolbar:false">// Connect to the database
$conn = new PDO('mysql:host=localhost;dbname=yourdbname', 'username', 'password');

// Prepare the SQL statement to insert data into the database
$stmt = $conn->prepare("INSERT INTO members (name, band_position, photo, about, other_bands) 
VALUES (:name, :band_position, :photo, :about, :other_bands)");

// Bind the parameters to the SQL statement
$stmt->bindParam(':name', $nameMember);
$stmt->bindParam(':band_position', $bandMember);
$stmt->bindParam(':photo', $photoName);
$stmt->bindParam(':about', $aboutMember);
$stmt->bindParam(':other_bands', $otherBands);

// Execute the SQL statement
$stmt->execute();

// Upload the image to the server
if (move_uploaded_file($_FILES['photo']['tmp_name'], $targetFilePath)) {
    // Image uploaded successfully
    echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the database.";
} else {
    // Image upload failed
    echo "Sorry, there was a problem uploading your file.";
}
登录后复制

} catch (PDOException $e) {

echo "Error: " . $e->getMessage();
登录后复制

}

$conn = null;
?>

在此代码中,我们使用 PDO 建立数据库连接并准备 SQL 语句将数据插入数据库。我们还将表单数据绑定到 SQL 参数并执行语句。最后,我们将图片上传到指定目录。

按照以下步骤,您可以成功将上传的文件名和其他信息存储到数据库中。

以上是PHP上传图片时如何将文件名存储在数据库中?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板