如何使用PHP参数绑定图像?

时间:2019-07-09 06:49:27

标签: php image prepared-statement

编辑:我的Ajax发送图像数据就是这个

  var Image = $('#PostSection').find('input[name="Image2"]').val();

    var fd = new FormData();
    var files = $('#Image2')[0].files[0];
    console.log(files);
    fd.append('Image',files);
    fd.append('username',username);
    fd.append('posts',posts);
    fd.append('backText3',backText3);
    fd.append('poll',poll);
    fd.append('option1',option1);
    fd.append('option2',option2);
    fd.append('option3',option3);
    fd.append('option4',option4);
    $.ajax({
        url: '../Admin/Posts/Post.php',
        type: 'post',
        data: fd,
        contentType: false,
        processData: false,
        success:  function() {
     $('#AllPosts').prepend($('<div>').load(location.href + " 
#AllPosts>*"));
  $('#PostSection')[0].reset();
     var x = document.getElementById("snackbar2");
  x.className = "snackbar show";
  setTimeout(function(){ x.className = x.className.replace("show", ""); }, 
3000);

请记住,我只显示图像的变量,因为这与我的问题有关。无需告知用户名,帖子,投票等代码。这与我的问题无关。

这样检索我的图像

  $tmpName  = $_FILES['Image']['tmp_name'];
  $fp = fopen($tmpName, 'r');
  $Image = fread($fp, filesize($tmpName));
  $Image = addslashes($Image);
  fclose($fp); 

我的插入代码就是这样

$stmt = $conn3->prepare("INSERT INTO `$Username` (Username,RepostedBy,RepostedId,Texts,Img,backText,Dates,TimeUploaded,EditedVersion,Likes,Repost,Tags,Poll)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");

$stmt->bind_param("ssssbssssssss",$Username,$RepostedBy,$RepostedId,$Texts,$Image,$BackText,$Date,$Time,$EditedVersion,$Likes,$Shares,$Tags,$Poll);

由于某种原因,这不起作用。我的图像专栏是longblob。插入了所有其他内容,但是由于某些原因未正确插入图像。文件被插入,但不是图像。 请注意,如我所说,在注释之前,所有内容均应按原样插入,但图像未正确插入。我不需要任何询问就我与数据库的连接或我的任何变量是否为空的答复。谢谢!

要插入的文件是图像,我的数据库对其中一些文件说129 kib,当图像的存储空间不应该那么高时。我尝试了这种不专业的方法

$sql = "INSERT INTO `$Username` (Username,RepostedBy,RepostedId,Texts,Img,backText,Dates,TimeUploaded,EditedVersion,Likes,Repost,Tags,Poll) 
VALUES ('$Username','$RepostedBy','$RepostedId','$Texts','$Image','$BackText','$Date','$Time','$EditedVersion','$Likes','$Shares','$Tags','$Poll');";

这有效,但它不是预准备的语句,因此它根本不是理想的选择,也不是专业的,因为我不想进行SQL注入。

2 个答案:

答案 0 :(得分:0)

确保已完全读取内容。 fread缓冲区大小应正确,以使完整的图像数据有效。尝试使用file_get_contents一次。

$Image = addslashes(file_get_contents($_FILES['Image']['tmp_name']));

答案 1 :(得分:0)

不建议将图像存储在数据库中,检索速度慢,一切都变慢。

人们要做的是,将图像存储在CDN,AWS S3或您喜欢的任何提供程序中,然后在数据库中存储URL。

真的不建议您做您想做的事。