【问题标题】:pdo insert image into database directly - always inserting BLOB - 0Bpdo 将图像直接插入数据库 - 始终插入 BLOB - 0B
【发布时间】:2014-07-14 06:42:45
【问题描述】:

我正在尝试将图像直接插入到 mysql 数据库表中。在我的数据库中,我总是得到 [BLOB - 0B]。它不会将图像插入表中。我也没有收到任何错误。我很困惑..

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>

【问题讨论】:

  • $data 变量是否保存了您期望的数据(如果您转储它)?表格中的图片字段是什么类型的?
  • @RonniSkansing:BLOB
  • 旁注:插入blob不是一个好主意,只需将图像存储在服务器的某个文件夹中,然后将url保存在表中
  • @user790454 It depends.
  • @FerozAkbar 为什么?似乎没有正当理由这么说,只是基于个人品味的 50/50 偏好。

标签: php mysql pdo blob


【解决方案1】:

你几乎明白了,你希望PDO::PARAM_LOB 是你在上面创建的文件指针,而不是读取 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();
}

【讨论】:

  • 没有。现在它不会在字段中插入任​​何数据。现在我的桌子上没有BLOB-0B..
  • @Beginner - 你确定$_FILES 数组已经被填充了吗?
  • 对不起。问题不在我的 php 编码中。这是我的错。我错过了在我的表格 enctype="multipart/form-data" 上提及这一点。无论如何,谢谢队友...
  • @Beginner - 如果这回答了您的问题,您应该 +1 并接受。您还可以编辑您的帖子以提及 enctype 更改。
猜你喜欢
  • 2017-03-23
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多