gpt4 book ai didi

php - 将二进制文件插入 MySQL BLOB

转载 作者:行者123 更新时间:2023-12-01 00:41:54 24 4
gpt4 key购买 nike

$serv = "xxx";
$user = "xxx";
$pass = "xxx";
$db = "xxx";

$imgloc = "../images/bg.jpg";
$image = fopen($imgloc, 'rb');
$imageContent = fread($image, filesize($imgloc));

$conn = new mysqli($serv, $user, $pass, $db);

$sql = "INSERT INTO `image`(`advert_id`,`img`) VALUES('1','" . $imageContent . "');";
$conn->query($sql);

我正在使用上面的代码尝试将二进制文件插入我的 MySQL 数据库,但没有任何内容被发送到数据库。 $imageContent 在数据库中显示为空,但如果我回显 $imageContent,它似乎显示二进制数据。

advert_id 只是一个 int 字段,img 是一个 BLOB

最佳答案

您的代码无法正常工作的原因是您需要转义数据。

$imageContent = fread($image, filesize($imgloc)); 
$imageContent = mysqli_real_escape_string($conn, $imageContent);

您没有看到语法错误,类似于:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '8 16@#54' at line 1...

  • 因为您没有检查错误。

访问http://php.net/manual/en/mysqli.error.phphttp://php.net/manual/en/function.error-reporting.php ,然后在文件顶部使用以下内容:

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// rest of your code

这将表示语法错误。


使用mysqli with prepared statements , 或 PDO with prepared statements


另外,正如 Mike Brant 在评论中所说,我引用:

“作为切线评论,我建议确保您确实有一个很好的用例来在 MySQL 中存储图像 blob。在很多情况下,与简单存储相比,这可能不是一个好主意数据库中的文件引用。”

  • 迈克说的是实话。随着时间的推移,您的数据库会急剧增加,因此将您的文件副本存储在一个文件夹中然后引用它通常是一个更好的主意,但这完全取决于您。

阅读 Stack 上的以下问答:

关于php - 将二进制文件插入 MySQL BLOB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30174824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com