【问题标题】:PHP: Inserting Blob Image to SQLite tablePHP:将 Blob 图像插入 SQLite 表
【发布时间】:2013-03-21 14:01:24
【问题描述】:

我正在尝试使用 (cakephp) 将图像插入到 BLOB 列中的 sqlite DB。

我正在使用此代码

$insert = "INSERT INTO story (page, image) 
                    VALUES (:page, :image)";
        $stmt = $file_db->prepare($insert);

        // Bind parameters to statement variables
        $img = file_get_contents($this->request->data['image']['tmp_name']);
        $img = mysql_real_escape_string($img);
        $stmt->bindParam(':page', $this->request->data['page']);
        $stmt->bindParam(':image', $img);

           // Execute statement
          $stmt->execute();

它正在插入,但字符集不是 Blob 数据,因为它应该是.. 有没有其他方法可以做到这一点,否则我的代码有什么问题?

【问题讨论】:

  • 不要使用blob,而是将图像存储在一个文件夹中并将filename.extension保存在SQL中,这样它就不会增加你的数据库大小
  • 你得到了什么字符集?
  • 我必须将它保存在 DB 上 :) 因为这个 DB 应该稍后转移到 Android :) 并且字符集类似于 PNG\r\n\Z\n\0\0\ 0\rIHDR\0\0,\0\0�\0\0\0\Z/��\0\0\0 pHYs\0\0\0\0\0��\ 0\0\0 cHRM\0\0z%\0\0��\0\0��\0\0��\0\0u0\0\0�`\0\0 :�\0\0o�_�F\0��IDATxÚ����u&\n�}������Ld&��0%\ 0\0��8I\"EÊL[�e�eW���Uv����j���������z]ï ¿½ï¿½ï¿½ï¿½êª®zU�T�m�$K�HM�(��L\0�\0cN�y��F�9g�;��sï ¿½^�_.JH�!��9{ï¿
  • 请发布您的 php、cake 和 sqlite 版本。
  • 我觉得这里不需要mysql_real_escape_string()

标签: php sqlite cakephp blob


【解决方案1】:

对标题中问题的回答,因为它在 [php sqlite blob] 中排名第一。这不使用 PDO,因为我遇到了麻烦。您必须使用准备好的语句,通常无法执行文字 SQL 插入,因为 blob 的大小太大。这是更新而不是插入,但基本相同。

// example variables
$row_id=1;
$image_filename="/home/mywebsite/public_html/images/an_image.png";
$sqlite_table_name="user_images";
$database_filename="database.sqlite";
// the blob field in the sqlite table is called ZIMAGE and the id field is ZID.

// Code
if (file_exists($image_filename)) {
$db = new SQLite3($database_filename);
$query = $db->prepare("UPDATE '{$sqlite_table_name}' SET ZIMAGE=? WHERE ZID=?");
$image=file_get_contents($image_filename);
$query->bindValue(1, $image, SQLITE3_BLOB);
$query->bindValue(2, $row_id, SQLITE3_TEXT);
$run=$query->execute();
}

我认为编程中没有任何硬性规则,在某些情况下,我将图像存储在 Sqlite 中的 blob 中。我还使用正则表达式而不是 Xpath 来抓取网页!无论做什么都能完成。

【讨论】:

  • 各位,请记住 $db->e​​scapeString 不是我认为的二进制安全的,所以感谢您的解决方案!
【解决方案2】:

这不是一个答案,但这个问题“不清楚”,太长了,不能作为评论

  1. 你提到了 CakePHP,但你的问题中没有涉及到 CakePHP
  2. 您提到了“SQLite”,但您使用的是 mysql_real_escape?

请说明您打算使用什么数据库。

关于 MySQL 和在数据库中存储图像;

  • PHP 中的 mysql_ 函数已弃用并且不再维护
  • 尝试确定您是否真的需要将图像存储在数据 内部数据库中,通常情况下,最好将图像本身存储在文件系统和数据库中图像的名称

阅读此问题以获得有关在 mysql 中插入图像的答案:

Insert Blobs in MySql databases with php

阅读此问题以获取有关在 SQLite 中插入图像(使用 PDO)的答案:

Remote image file to sqlite blob in PHP?

这是针对 BLOB 的通用 PDO 逐步演练;

http://www.phpeveryday.com/articles/PDO-Working-With-BLOBs-P554.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-25
    • 2012-05-20
    • 2012-11-08
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 2021-02-17
    相关资源
    最近更新 更多