图像在mysql数据库中上传和显示

时间:2017-03-25 07:19:40

标签: php mysql

我需要在mysql数据库中上传一个图像,它应该在需要时显示在表格中。我使用以下代码存储在数据库中。

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

<input type="submit" value="Save" name="submit">

<?php
    mysql_connect("localhost", "root", ""); mysql_select_db("prs");
    if(isset($_POST['submit']))
    {
      $errors= array();
      $file_name=$_FILES['photo']['name'];
      $file_size =$_FILES['photo']['size'];
      $file_tmp =$_FILES['photo']['tmp_name'];
      $file_type=$_FILES['photo']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['photo']['name'])));
      $expensions= array("jpeg","jpg","png");
      if(in_array($file_ext,$expensions)=== false){
      $errors[]="extension not allowed, please choose a JPEG or PNG file.";
    }
      if($file_size > 2097152){
      $errors[]='File size must be excately 2 MB';
     }
     if(empty($errors)==true){
     move_uploaded_file($file_tmp,"images/".$file_name);
     echo '<script language="javascript">';
     echo 'alert("Success")';
     echo '</script>';
    }
    else
    {
      echo '<script language="javascript">'; echo 'alert("Failed")';
      echo '</script>';
      print_r($errors);
    }
    }
    $photo = $_FILES['photo'];
    {   
      $query = mysql_query("insert into e (photo) values ('$photo')");
      echo '<script language="javascript">'; echo 'alert("Employed")';
      echo '</script>';
    }
    else
    {
     echo'<script language="javascript">';echo 'alert("Insertions Failed")';
     echo '</script>';   
    }
}
    mysql_close($connection);
?>

以下代码用于在表单加载时显示数据库中的图像。

<form method="get" enctype="multipart/form-data">
              <table class="table table-bordered table-striped">
              <thead><tr><th>Photo</th></tr></thead>
              <tbody><tr>
                  <?php
                $connection = mysql_connect("localhost", "root", "");
                $db = mysql_select_db("prs", $connection);
                $sql = "SELECT * FROM e";
                $result = mysql_query($sql);
                while ($outw = mysql_fetch_assoc($result))
                {
                     echo "<tbody>";
                     echo "<tr>"; echo "<td>".'<img src="data:image/jpeg;base64,'.base64_encode( $result['photo'] ).'"/>' ."</td>"; echo "</tr>";
                     echo "</tbody>";
                }
                ?>
                </tr> 
              </tbody>
            </table>
            </form>

我使用博客作为照片的数据类型。上面的代码没有显示数据库中的图像。

1 个答案:

答案 0 :(得分:1)

在这里,您需要获取图像数据并以BLOB格式保存在数据库中:

$photo = file_get_contents($_FILES['photo']['tmp_name']);

Can I store images in MySQL