上传并显示图片php mysqli

时间:2016-03-30 04:55:55

标签: php image mysqli

我需要帮助我的显示图像,显示是正确的,但我不知道为什么图像不出现。

CREATE TABLE `images` (
  `id` int(11) NOT NULL,
  `name` varchar(100) DEFAULT NULL,
  `size` int(11) DEFAULT NULL,
  `type` varchar(20) DEFAULT NULL,
  `content` mediumblob
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

这是我的“ upload.php

<?php

// Check for post data.
if ($_POST && !empty($_FILES)) {
    $formOk = true;

    //Assign Variables
    $path = $_FILES['image']['tmp_name'];
    $name = $_FILES['image']['name'];
    $size = $_FILES['image']['size'];
    $type = $_FILES['image']['type'];

    if ($_FILES['image']['error'] || !is_uploaded_file($path)) {
        $formOk = false;
        echo "Error: Error in uploading file. Please try again.";
    }

    //check file extension
    if ($formOk && !in_array($type, array('image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/gif'))) {
        $formOk = false;
        echo "Error: Unsupported file extension. Supported extensions are JPG / PNG.";
    }
    // check for file size.
    if ($formOk && filesize($path) > 500000) {
        $formOk = false;
        echo "Error: File size must be less than 500 KB.";
    }

    if ($formOk) {
        // read file contents
        $content = file_get_contents($path);

        //connect to mysql database
        if ($conn = mysqli_connect('localhost', 'root', '', 'upload')) {
            $content = mysqli_real_escape_string($conn, $content);
            $sql = "insert into images (name, size, type, content) values ('{$name}', '{$size}', '{$type}', '{$content}')";

            if (mysqli_query($conn, $sql)) {
                $uploadOk = true;
                $imageId = mysqli_insert_id($conn);
            } else {
                echo "Error: Could not save the data to mysql database. Please try again.";
            }

            mysqli_close($conn);
        } else {
            echo "Error: Could not connect to mysql database. Please try again.";
        }
    }
}
?>

<html>
    <head>
        <title>Upload image to mysql database.</title>
        <style type="text/css">
            img{
                margin: .2em;
                border: 1px solid #555;
                padding: .2em;
                vertical-align: top;
            }
        </style>
    </head>
    <body>
        <?php if (!empty($uploadOk)): ?>
            <div>
                <h3>Image Uploaded:</h3>
            </div>
            <div>
                <img src="image.php?id=<?=$imageId ?>" width="150px">
                <strong>Embed</strong>: <input size="25" value='<img src="image.php?id=<?=$imageId ?>">'>
            </div>

            <hr>
        <?php endif; ?>

        <form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data" >
          <div>
            <h3>Image Upload:</h3>
          </div>
          <div>
            <label>Image</label>
            <input type="hidden" name="MAX_FILE_SIZE" value="500000">
            <input type="file" name="image" />
            <input name="submit" type="submit" value="Upload">
          </div>
        </form>
    </body>
</html>

然后这是我的“ image.php

<?php

    // verify request id.
    if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
        echo 'A valid image file id is required to display the image file.';
        exit;
    }

    $imageId = $_GET['id'];

    //connect to mysql database
    if ($conn = mysqli_connect('localhost', 'root', '', 'upload')) {
        $content = mysqli_real_escape_string($conn, $content);
        $sql = "SELECT type, content FROM images where id = {$imageId}";

        if ($rs = mysqli_query($conn, $sql)) {
            $imageData = mysqli_fetch_array($rs, MYSQLI_ASSOC);
            mysqli_free_result($rs);
        } else {
            echo "Error: Could not get data from mysql database. Please try again.";
        }
        //close mysqli connection
        mysqli_close($conn);

    } else {
        echo "Error: Could not connect to mysql database. Please try again.";
    }   

    if (!empty($imageData)) {
        // show the image.
        header("Content-type: {$imageData['type']}");
        echo $imageData['content'];
    }
?>

每次我尝试上传图片时都会成功,但我上传的图片没有显示。但这只出现图像错误。请有人帮我吗?

或者有没有人可以给我一个如何使用数据库上传和显示图像的教程?

2 个答案:

答案 0 :(得分:0)

    <?php
     error_reporting( ~E_NOTICE );
     require_once 'dbconfig.php';
 
     if(isset($_GET['edit_id']) && !empty($_GET['edit_id']))
      {
      $id = $_GET['edit_id'];
      $stmt_edit = $DB_con->prepare('SELECT userName, userProfession, userPic FROM 
        tbl_users 
         WHERE userID =:uid');
        $stmt_edit->execute(array(':uid'=>$id));
        $edit_row = $stmt_edit->fetch(PDO::FETCH_ASSOC);
        extract($edit_row);
      }
      else
       {
      header("Location: index.php");
      }
 
      if(isset($_POST['btn_save_updates']))
     {
      $username = $_POST['user_name'];// user name
      $userjob = $_POST['user_job'];// user email
   
      $imgFile = $_FILES['user_image']['name'];
      $tmp_dir = $_FILES['user_image']['tmp_name'];
      $imgSize = $_FILES['user_image']['size'];
     
      if($imgFile)
       {
         $upload_dir = 'user_images/'; // upload directory 
         $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
         $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
         $userpic = rand(1000,1000000).".".$imgExt;
         if(in_array($imgExt, $valid_extensions))
         {   
          if($imgSize < 5000000)
         {
           unlink($upload_dir.$edit_row['userPic']);
          move_uploaded_file($tmp_dir,$upload_dir.$userpic);
       }
       else
       {
       $errMSG = "Sorry, your file is too large it should be less then 5MB";
      }
      }
      else
      {
      $errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";  
      } 
     }
      else
      {
     // if no image selected the old image remain as it is.
     $userpic = $edit_row['userPic']; // old image from database
    } 
      
  
     // if no error occured, continue ....
     if(!isset($errMSG))
      {
        $stmt = $DB_con->prepare('UPDATE tbl_users 
              SET userName=:uname, 
               userProfession=:ujob, 
               userPic=:upic 
               WHERE userID=:uid');
              $stmt->bindParam(':uname',$username);
              $stmt->bindParam(':ujob',$userjob);
              $stmt->bindParam(':upic',$userpic);
              $stmt->bindParam(':uid',$id);
    
           if($stmt->execute()){
        ?>
                <script>
    alert('Successfully Updated ...');
    window.location.href='index.php';
    </script>
                <?php
   }
   else{
    $errMSG = "Sorry Data Could Not Updated !";
   }
  }    
 }
?>

答案 1 :(得分:-1)

您必须暂时提取['content']。像这样:

    $rs = mysqli_query($conn, $sql);
    while ( $imageData = mysqli_fetch_assoc($rs) ) {
        $content = $imageData['content'];
    }
    header("Content-type: $content ");
    echo $content;

我会建议您检查和更改:

$sql = "SELECT type, content FROM images where id = {$imageId}"; 

代表

$sql = "SELECT type, content FROM images where id = '$imageId' ";