首页 > 解决方案 > 为什么将图像上传到数据库时出错?

问题描述

我想使用 PHP 将图像上传到数据库中。尝试上传时出现以下错误:

Error: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 '' at line 1
dbname:img    
tablename:image   
column:img   
type:LongBLob.

我之前已经设法连接到数据库并且能够插入除图像内容之外的任何内容。这是我的代码:

<form method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <button>Go</button>
</form>

<?php
  $C = new mysqli("localhost","root","","img");

  if(!$C->error) {
    echo "Connected";
  } else {
    echo $C->error;
  }

  if(isset($_FILES['file'])) {
    $F = file_get_contents($_FILES['file']['tmp_name']);
    $Q = "insert into image (img) values('$F')";
    $R = $C->query($Q);
    if($R == true) {
      echo "ok";
    } else {
      echo $C->error;
    }
  }
?>

标签: phphtml

解决方案


You get this error because you're essentially taking the raw contents of the file, and dumping it into the SQL statement without any form of sanitizing, or encoding.

Try: addslashes

Simply using addslashes would escape any conflicting characters that would cause the SQL query to fail.

$F = file_get_contents($_FILES['file']['tmp_name']);
$data = addslashes($F);
$Q = "insert into image (img) values('$data')";

Try: base64_encode

An alternative may be to use base64_encode instead.

Note: When using this method, your img column should be of type TEXT

$F = file_get_contents($_FILES['file']['tmp_name']);
$encoded = base64_encode($F);
$Q = "insert into image (img) values('$encoded')";

When retrieving the value from the database, you'll need to base64_decode in order to get the raw data back again.


推荐阅读