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

将二进制文件插入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

图片转代码服务由CSDN问答提供 功能建议

  $ 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只是在数据库中显示为null但是如果我回显$ imageContent它似乎显示二进制数据。

advert_id只是一个int字段而img是一个BLOB \ n

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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:

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题