使用php将照片(blob)插入数据库时遇到了很大的问题。我无法执行查询。它返回false。这是我的代码
<div class="swiper-viewport">
<div id="slideshow{{ module }}" class="swiper-container">{% set i = 1 %}
<div class="swiper-wrapper"> {% for banner in banners %}
<div class="swiper-slide s-slide-{{ i }} text-center">
<img src="{{ banner.image }}" alt="" class="img-responsive" />
<div class="banner-desc">{{ banner.title }}
{% if banner.link %}<a class="btn-slider" href="{{ banner.link }}">SHOP NOW</a>
{% endif %}
答案 0 :(得分:1)
PDO解决方案
假设您正在使用PDO(未由您指定),如果您想将其保存为blob,则应执行以下步骤
try
{
$fp = fopen($_FILES['fic']['tmp_name'], 'rb'); // read the file as binary
$stmt = $conn->prepare("INSERT INTO image (titre, selogon, description, img_blob) VALUES (?, ?, ?, ?)"); // prepare statement
// bind params
$stmt->bindParam(1, $img_titre);
$stmt->bindParam(2, $selogon);
$stmt->bindParam(3, $description);
// this is important I will explain it below after the code
$stmt->bindParam(4, $fp, PDO::PARAM_LOB);
$stmt->execute();
// if you want to check if it was inserted use affected rows from PDO
}
catch(PDOException $e)
{
'Error : ' .$e->getMessage();
}
最重要的是将文件指针($ fp)绑定到名为LOB的PDO param,它代表大对象
PDO :: PARAM_LOB告诉PDO将数据映射为流,以便您可以使用PHP Streams API对其进行操作。
http://php.net/manual/en/pdo.lobs.php
之后,您可以使用PHP流的强大功能并将其保存为二进制安全流。从流中读取更有意义,但如果我是你,我真的认为如果你想直接在db中保存图片,这似乎不是一个好主意。
MYSQLI解决方案:
如果您不使用PDO,例如mysqli,那么流也是好主意,但解决方案是不同的。
最好的选择是检查SHOW VARIABLES LIKE 'max_allowed_packet';
这将打印允许的最大包大小,如果您的图像更大,则blob将被损坏。
要使其工作,您需要使用fread()+ loop + feof()和mysqli函数send_long_data
以较小的块发送数据Example from php.net site:你可以根据你的需要调整它,就像我上面那样,不同之处在于params以不同的方式绑定。
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen($_FILES['fic']['tmp_name'], "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
答案 1 :(得分:0)
我一直在解决这个问题: 解决方案:增加类型(blob - &gt; longblob)中照片的大小。