Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

php - pdo insert image into database directly - always inserting BLOB - 0B

I'm trying to insert the image into mysql database table directly. In my database I'm always getting [BLOB - 0B]. it doesn't insert images into table. I didn't get any error too. I'm confused..

PHP

ini_set('display_startup_errors',1);
    ini_set('display_errors',1);
    error_reporting(-1);

    include('config.php');
     if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) 
      { 
          $tmpName  = $_FILES['image']['tmp_name'];  

          $fp = fopen($tmpName, 'r');
          $data = fread($fp, filesize($tmpName));
          $data = addslashes($data);
          fclose($fp);
      } 

      try
        {
            $stmt = $conn->prepare("INSERT INTO images ( picture ) VALUES ( '$data' )");
//          $stmt->bindParam(1, $data, PDO::PARAM_LOB);
            $conn->errorInfo();
            $stmt->execute();
        }
        catch(PDOException $e)
        {
            'Error : ' .$e->getMessage();
        }

HTML

<form action="upload.php" method="post">
<input id="image" name="image" type="file" />
<input type="submit" value="Upload" />
</form>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You almost got it, you want PDO::PARAM_LOB to be a file pointer which you created above, not the result of reading the fp

if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) 
{ 
   $tmpName  = $_FILES['image']['tmp_name'];  

   $fp = fopen($tmpName, 'rb'); // read binary
} 

try
{
   $stmt = $conn->prepare("INSERT INTO images ( picture ) VALUES ( ? )");
   $stmt->bindParam(1, $fp, PDO::PARAM_LOB);
   $conn->errorInfo();
   $stmt->execute();
}
catch(PDOException $e)
{
   'Error : ' .$e->getMessage();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...