doulang9953 2015-05-11 18:17
浏览 184
已采纳

将二进制文件插入MySQL BLOB

$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);

I'm using the above code to try to insert binary into my MySQL database but nothing is being sent to the database. The $imageContent just appears in the database as null but if I echo $imageContent it seems to show binary data.

advert_id is just a int field and img is a BLOB

  • 写回答

1条回答 默认 最新

  • dsjklb0205 2015-05-11 18:50
    关注

    The reason why your code isn't working is because you need to escape your data.

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

    You are not seeing the syntax error, similar to:

    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...

    • Because you are not checking for errors.

    Visit http://php.net/manual/en/mysqli.error.php and http://php.net/manual/en/function.error-reporting.php, then use the following at the top of your file:

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

    This will signal syntax errors.


    Use mysqli with prepared statements, or PDO with prepared statements


    Plus, as Mike Brant said in comments, and I quote:

    "As a tangential comment, I would recommend making sure that you REALLY have a good use case for storing images blobs in MySQL. In a lot of cases, this might not be a good idea when compared to simply storing file references in the database."

    • Mike speaks the truth. Your database will increase dramatically over time, therefore storing a copy of your files in a folder then making a reference to it, is usually a better idea, but that is entirely up to you.

    Read the following Q&A's on Stack:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况