首页 >数据库 >mysql教程 >如何在上传过程中高效地将图像文件名存储在数据库中?

如何在上传过程中高效地将图像文件名存储在数据库中?

Barbara Streisand
Barbara Streisand原创
2024-11-30 00:02:10826浏览

How to Efficiently Store Image Filenames in a Database During an Upload?

上传图像时将文件名存储在数据库中

挑战:

将图像上传到服务器并将其文件名存储在数据库中,同时捕获其他表单数据构成了常见的挑战网络开发人员。

解决方案:

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn