将BLOB数据插入数据库

PHP PDO提供了使用流和prepare语句处理BLOB数据的便捷方法。
要将文件的内容插入BLOB列,请按照以下步骤操作:

  • 首先,打开文件以二进制模式读取。

  • 其次,构造一个INSERT语句。

  • 第三,使用bindParam()方法将文件句柄绑定到准备好的语句,然后调用execute()方法执行查询。

请参见以下insertBlob()方法:

/**
     * insert blob into the files table
     * @param string $filePath
     * @param string $mime mimetype
     * @return bool
     */
    public function insertBlob($filePath, $mime) {
        $blob = fopen($filePath, 'rb');

        $sql = "INSERT INTO files(mime,data) VALUES(:mime,:data)";
        $stmt = $this->pdo->prepare($sql);

        $stmt->bindParam(':mime', $mime);
        $stmt->bindParam(':data', $blob, PDO::PARAM_LOB);

        return $stmt->execute();
    }

请注意,PDO :: PARAM_LOB指示PDO将数据映射为流。

PHP MySQL的BLOB

简介:在本教程中,您将学习如何使用PHP PDO处理BLOB数据。
我们将向您展示如何在MySQL数据库中插入,更新和选择BLOB数据。

有时出于安全原因,您可能需要在MySQL数据库中存储大型数据对象,例如图像,PDF文件和视频。

MySQL提供了可以容纳大量数据的BLOB类型。
BLOB代表二进制大数据对象。
BLOB对象的最大值由可用内存和通信包大小指定。
您可以使用MySQL中的max_allowed_pa​​cket变量和PHP设置中的post_max_size来更改通信包的大小。

让我们看看PHP PDO如何处理MySQL中的BLOB类型。

首先,我们在示例数据库中创建一个名为files的新表进行练习。

文件表包含三列:

  • id列是主键,自动递增列。

  • MIME列存储文件的MIME类型。

  • 数据列,其数据类型是BLOB,用于存储文件的内容。

以下CREATE TABLE语句创建files表:

CREATE TABLE files (
    id   INT           AUTO_INCREMENT PRIMARY KEY,
    mime VARCHAR (255) NOT NULL,
    data BLOB          NOT NULL
);

其次,我们使用以下代码定义一个名为BlobDemo的类:

<?php

/**
 * PHP MySQL BLOB Demo
 */
class BobDemo {

    const DB_HOST = 'localhost';
    const DB_NAME = 'classicmodels';
    const DB_USER = 'root';
    const DB_PASSWORD = '';

    /**
     * Open the database connection
     */
    public function __construct() {
        // open database connection
        $conStr = sprintf("mysql:host=%s;dbname=%s;charset=utf8", self::DB_HOST, self::DB_NAME);

        try {
            $this->pdo = new PDO($conStr, self::DB_USER, self::DB_PASSWORD);
            //for prior PHP 5.3.6
            //$conn->exec("set names utf8");
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }

    /**
     * close the database connection
     */
    public function __destruct() {
        // close the database connection
        $this->pdo = null;
    }

}

在__construct()方法中,我们打开到MySQL数据库的数据库连接,在__destruct()方法中,我们关闭了连接。

PHP MySQL BLOB示例

在以下示例中,我们将使用BlobDemo类将GIF图像和PDF文件保存到files表的BLOB列中。

PHP MySQL BLOB与图像文件

首先,我们将来自images / php-mysql-blob.gif文件的二进制数据插入到文件表的BLOB列中,如下所示:

$blobObj = new BlobDemo();

// test insert gif image
$blobObj->insertBlob('images/php-mysql-blob.gif',"image/gif");

然后,我们可以选择BLOB数据并将其显示为GIF图像:

$a = $blobObj->selectBlob(1);
header("Content-Type:" . $a['mime']);
echo $a['data'];

PHP MySQL BLOB与PDF文件

以下代码将pdf / php-mysql-blob.pdf PDF文件的内容插入到BLOB列中:

$blobObj = new BlobDemo();

// test insert pdf
$blobObj->insertBlob('pdf/php-mysql-blob.pdf',"application/pdf");

然后,我们可以选择PDF数据并将其呈现在Web浏览器中,如下所示:

$a = $blobObj->selectBlob(2);
header("Content-Type:" . $a['mime']);
echo $a['data'];

要将PDF文件替换为GIF图像文件,请使用updateBlob()方法,如下所示:

$blobObj->updateBlob(2, 'images/php-mysql-blob.gif', "image/gif");

$a = $blobObj->selectBlob(2);
header("Content-Type:" . $a['mime']);
echo $a['data'];

您可以通过以下链接下载本教程的源代码:

下载PHP MySQL BLOB源代码

在本教程中,我们向您展示了如何管理MySQL BLOB数据,包括插入,更新和查询Blob。

更新现有的BLOB列

要更新BLOB列,请使用与将数据插入到BLOB列中所述的相同技术。
请参见以下updateBlob()方法:

/**
     * update the files table with the new blob from the file specified
     * by the filepath
     * @param int $id
     * @param string $filePath
     * @param string $mime
     * @return bool
     */
    function updateBlob($id, $filePath, $mime) {

        $blob = fopen($filePath, 'rb');

        $sql = "UPDATE files
                SET mime = :mime,
                    data = :data
                WHERE id = :id;";

        $stmt = $this->pdo->prepare($sql);

        $stmt->bindParam(':mime', $mime);
        $stmt->bindParam(':data', $blob, PDO::PARAM_LOB);
        $stmt->bindParam(':id', $id);

        return $stmt->execute();
    }

从BLOB列查询数据

以下步骤描述了如何从BLOB列中选择数据:

  • 首先,构造一个SELECT语句。

  • 其次,使用PDOStatement对象的bindColumn()方法绑定相应的参数。

  • 第三,执行语句。

请参见以下selectBlob()方法:

/**
     * select data from the the files
     * @param int $id
     * @return array contains mime type and BLOB data
     */
    public function selectBlob($id) {

        $sql = "SELECT mime,
                        data
                   FROM files
                  WHERE id = :id;";

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(array(":id" => $id));
        $stmt->bindColumn(1, $mime);
        $stmt->bindColumn(2, $data, PDO::PARAM_LOB);

        $stmt->fetch(PDO::FETCH_BOUND);

        return array("mime" => $mime,
            "data" => $data);
    }
日期:2019-11-20 08:52:37 来源:oir作者:oir