【问题标题】:How to store images in mysql database using php如何使用php将图像存储在mysql数据库中
【发布时间】:2015-01-01 16:07:49
【问题描述】:

如何在 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.";}

【问题讨论】:

  • 我不建议将图像存储在数据库中,您目前所做的是更好的方法。您需要做的就是将图像的路径存储在数据库中
  • 感谢您的帮助,我想通了。现在我只是将上传文件的名称存储在我的数据库中并检索该名称以在我想要的任何位置打开图像。

标签: php html mysql image-uploading


【解决方案1】:

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

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";
}

【讨论】:

  • 用户可能有正当理由将图像上传到数据库,并且可以执行。它只是不是很受欢迎,因此没有得到很好的“支持”(即知识库不太广泛)
  • 警告:上面的示例代码对于 SQL 注入漏洞是开放的。
  • @Oy3 你正在删除一个 5 年前的评论。学习 SQL 注入是每个开发者都应该做的练习,网上有很多例子。在这种情况下,我不会在我 5 岁的警告中提供更好的方法....
【解决方案2】:
if(isset($_POST['form1']))
{
    try
    {


        $user=$_POST['username'];

        $pass=$_POST['password'];
        $email=$_POST['email'];
        $roll=$_POST['roll'];
        $class=$_POST['class'];



        if(empty($user)) throw new Exception("Name can not empty");
        if(empty($pass)) throw new Exception("Password can not empty");
        if(empty($email)) throw new Exception("Email can not empty");
        if(empty($roll)) throw new Exception("Roll can not empty");
        if(empty($class)) throw new Exception("Class can not empty");


        $statement=$db->prepare("show table status like 'tbl_std_info'");
        $statement->execute();
        $result=$statement->fetchAll();
        foreach($result as $row)
        $new_id=$row[10];


        $up_file=$_FILES["image"]["name"];

        $file_basename=substr($up_file, 0 , strripos($up_file, "."));
        $file_ext=substr($up_file, strripos($up_file, ".")); 
        $f1="$new_id".$file_ext;

        if(($file_ext!=".png")&&($file_ext!=".jpg")&&($file_ext!=".jpeg")&&($file_ext!=".gif"))
        {
            throw new Exception("Only jpg, png, jpeg or gif Logo are allow to upload / Empty Logo Field");
        }
        move_uploaded_file($_FILES["image"]["tmp_name"],"../std_photo/".$f1);


        $statement=$db->prepare("insert into tbl_std_info (username,image,password,email,roll,class) value (?,?,?,?,?,?)");

        $statement->execute(array($user,$f1,$pass,$email,$roll,$class));


        $success="Registration Successfully Completed";

        echo $success;
    }
    catch(Exception $e)
    {
        $msg=$e->getMessage();
    }
}

【讨论】:

  • 欢迎提供解决问题的代码,但请添加一些解释。 (使示例尽可能小也是一个好主意)
【解决方案3】:

插入图片zh

-当我们使用插入查询在数据库中插入图像时

$Image = $_FILES['Image']['name'];
    if(!$Image)
    {
      $Image="";
    }
    else
    {
      $file_path = 'upload/';
      $file_path = $file_path . basename( $_FILES['Image']['name']);    
      if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path)) 
     { 
}
}

【讨论】:

    【解决方案4】:
    <!-- 
    //THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
    (IF YOU HAVE ANY QUERY CONTACT:rahulpatel541@gmail.com)
    
    
    CREATE TABLE  `images` (
      `id` int(100) NOT NULL AUTO_INCREMENT,
      `name` varchar(100) NOT NULL,
      `image` longblob NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB ;
    
    -->
    <!-- this form is user to store images-->
    <form action="index.php" method="post"  enctype="multipart/form-data">
    Enter the Image Name:<input type="text" name="image_name" id="" /><br />
    
    <input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
    <input type="submit" value="submit" name="submit" />
    </form>
    <br /><br />
    <!-- this form is user to display all the images-->
    <form action="index.php" method="post"  enctype="multipart/form-data">
    Retrive all the images:
    <input type="submit" value="submit" name="retrive" />
    </form>
    
    
    
    <?php
    //THIS IS INDEX.PHP PAGE
    //connect to database.db name is images
            mysql_connect("", "", "") OR DIE (mysql_error());
            mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
    //to retrive send the page to another page
    if(isset($_POST['retrive']))
    {
        header("location:search.php");
    
    }
    
    //to upload
    if(isset($_POST['submit']))
    {
    if(isset($_FILES['image'])) {
            $name=$_POST['image_name'];
            $email=$_POST['mail'];
            $fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
            }
                    // our sql query
                    $sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
                                mysql_query($sql) or die("Error in Query insert: " . mysql_error());
    } 
    ?>
    
    
    
    <?php
    //SEARCH.PHP PAGE
        //connect to database.db name = images
             mysql_connect("localhost", "root", "") OR DIE (mysql_error());
            mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
    //display all the image present in the database
    
            $msg="";
            $sql="select * from images";
            if(mysql_query($sql))
            {
                $res=mysql_query($sql);
                while($row=mysql_fetch_array($res))
                {
                        $id=$row['id'];
                        $name=$row['name'];
                        $image=$row['image'];
    
                      $msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " />   </a>';
    
                }
            }
            else
                $msg.="Query failed";
    ?>
    <div>
    <?php
    echo $msg;
    ?>
    

    【讨论】:

    • 充满了安全漏洞。
    猜你喜欢
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 2017-07-22
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    相关资源
    最近更新 更多