【问题标题】:How do i insert a image in a database and be able to show it again? [closed]如何在数据库中插入图像并能够再次显示? [关闭]
【发布时间】:2019-09-06 12:28:35
【问题描述】:

我正在尝试在数据库中插入图像,然后再次显示。 目前它不起作用。 所以我的问题是如何插入图片然后在页面上显示。

尝试插入和选择,但不起作用

【问题讨论】:

    标签: php html sql database image


    【解决方案1】:

    如果你想用 php 上传和显示文件试试:

    1) 首先,您将文件上传到一个文件夹。 This tutorial 可以帮助你用 PHP 上传文件。

    2) 在您的数据库上创建一个名为 "uploaded_files" 的表,并在该表下创建像 "id, file_url" 的字段。

    3) 在上传过程中将 $target_file 值保存到 file_url 字段并从数据库中获取。

    但如果您想使用 blob 将文件保存在数据库中,this tutorial 可能会对您有所帮助。


    在 php 上试试:

    CREATE TABLE `uploaded_files` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `file_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    

    连接名为“db_conenct.php”的数据库:

    <?php
    // Database configuration
    $dbHost     = "localhost";
    $dbUsername = "user";
    $dbPassword = "pass";
    $dbName     = "your_database_name";
    
    // Create database connection
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
    
    // Check connection
    if ($db->connect_error) {
        die("Connection failed: " . $db->connect_error);
    }
    ?>
    

    使用 HTML 创建上传表单,您将使用“POST”方法将数据发送到 upload.php:

    <form action="upload.php" method="post" enctype="multipart/form-data">
        Select Image File to Upload:
        <input type="file" name="file">
        <input type="submit" name="submit" value="Upload">
    </form>
    

    上传.php

    <?php
    // Include the database configuration file
    include 'db_connect.php';
    $statusMsg = '';
    
    // File upload path
    $targetDir = "uploads/";
    $fileName = basename($_FILES["file"]["name"]);
    $targetFilePath = $targetDir . $fileName;
    $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
    
    if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
        // Allow certain file formats
        $allowTypes = array('jpg','png','jpeg','gif','pdf');
        if(in_array($fileType, $allowTypes)){
            // Upload file to server
            if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
                // Insert image file name into database
                $insert = $db->query("INSERT into uploaded_files (file_url) VALUES ('".$fileName."'");
                if($insert){
                    $statusMsg = "The file ".$fileName. " has been uploaded successfully.";
                }else{
                    $statusMsg = "File upload failed, please try again.";
                } 
            }else{
                $statusMsg = "Sorry, there was an error uploading your file.";
            }
        }else{
            $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
        }
    }else{
        $statusMsg = 'Please select a file to upload.';
    }
    
    // Display status message
    echo $statusMsg;
    ?>
    

    显示上传的图片:

    <?php
    // Include the database configuration file
    include 'db_connect.php';
    
    // Get images from the database
    $query = $db->query("SELECT * FROM uploaded_files ORDER BY id DESC");
    
    if($query->num_rows > 0){
        while($row = $query->fetch_assoc()){
            $imageURL = 'uploads/'.$row["file_url"];
    ?>
        <img src="<?php echo $imageURL; ?>" alt="" />
    <?php }
    }else{ ?>
        <p>No image(s) found...</p>
    <?php } ?>
    

    【讨论】:

      【解决方案2】:

      我不知道我是否能很好地理解你的问题,但无论如何我都会尝试回答。

      在我看来,有两种方法可以做到:

      1. 将您的图像上传到任何存储图像的云或您的项目结构,并保存在数据库中的唯一图像路径。

      2. 获取文件内容,然后将其保存到您的数据库中,例如。

      $file = fopen($MY_FILE, 'r');
      $file_contents = fread($file, filesize($MY_FILE));
      fclose($file);
      
      /* escape some stcharacters in file_contents before query.*/
      $file_contents = addslashes($file_contents);
      
      // Add the file in the database
      mysql_connect('localhost', 'root', '') or die("Unable to connect to database.");
      mysql_select_db('test') or die("Unable to select the DB.");
      mysql_query("INSERT INTO files SET file_data='$file_contents'") or die("MySQL Query Error: " . mysql_error() . "
      
      ". "The SQL was: $SQL
      
      ");
      mysql_close();
      echo "File INSERTED into files table successfully.";
      

      要将文件二进制内容存储在数据库中,列必须是以下类型之一:

      • TINYBLOB
      • BLOB
      • MEDIUMBLOB
      • LONGBLOB

      【讨论】:

      • mysql_query 不存在。它已被删除!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      相关资源
      最近更新 更多