php - 如何使用php将图片存储到mysql数据库中

标签 php html mysql image-uploading

如何在 MySQL 数据库中存储和显示图像。到现在为止我只编写了从用户那里获取图像并将它们存储在文件夹中的代码,到目前为止我编写的代码是: HTML 文件

<input type="file" name="imageUpload" id="imageUpload">

PHP 文件

    $target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);


if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";}

最佳答案

我找到了答案,对于那些正在寻找同样东西的人,我就是这样做的。 您不应该考虑将图像上传到数据库,而是可以将上传文件的名称存储在数据库中,然后检索文件名并在您想要显示图像的任何地方使用它。

HTML 代码

<input type="file" name="imageUpload" id="imageUpload">

PHP 代码

if(isset($_POST['submit'])) {

    //Process the image that is uploaded by the user

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }

    $image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable

    //storind the data in your database
    $query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
    mysql_query($query);

    require('heading.php');
    echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
    header( "Refresh:3; url=account.php", true, 303);
}

显示图像的代码

while($row = mysql_fetch_row($result)) {
    echo "<tr>";
    echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
    echo "</tr>\n";
}

关于php - 如何使用php将图片存储到mysql数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26757659/

相关文章:

mysql - ansible galaxy - 从 repo 安装角色

mysql - 尝试导出 mysql 中的查询结果时出现 fatal error

javascript - 一个 promise 的 mysql 模块将如何与 NodeJS 一起工作?

php - 这种密码存储方式安全吗?

php - Laravel:由于某种原因无法使用

php - php如何转换 bool 变量?

javascript - 旋转木马图像相同高度

php - 如何在 PHP 中为 MongoDB 返回 ISO 日期格式?

python - 从html页面获取相关链接

javascript - 如何在不使用外部库的情况下语法突出显示可进行内容编辑的div?