尝试在MySql表中插入图像时PHP抛出错误?

时间:2014-05-08 03:38:32

标签: php mysql

我正在尝试将数据类型保存为MyBql表中的图像作为BLOB。但是,当它尝试插入MySql表时,我收到错误?有人可以解释什么是错的吗?以下是第37行

  

mysqli_query($ con," INSERT INTO image(image)VALUES   ($ _FILES [' file'] [' tmp_name'])");

错误

 Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\wamp\www\FileUpload\php\upload_file.php on line 37

HTML

<form action="php/upload_file.php" method="post" data-ajax="false" enctype="multipart/form-data">
 <label for="file">Filename:</label>
 <input type="file" name="file" id="file"><br>
 <input type="submit" name="submit" value="Submit">
</form>

PHP

<?php

$con=mysqli_connect("localhost","root","root123","deal_bank","3306");

if (mysqli_connect_errno())
  {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_select_db($con,"deal_bank");

$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] > 20000)
&& in_array($extension, $allowedExts)) {
  if ($_FILES["file"]["error"] > 0) {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
  } else {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
    if (file_exists("upload/" . $_FILES["file"]["name"])) {
      echo $_FILES["file"]["name"] . " already exists. ";
    } else {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      mysqli_query($con,"INSERT INTO image (image) VALUES ($_FILES['file']['tmp_name']) ");

    }
  }
} else {
  echo "Invalid file";
}

?>

MySQL表

CREATE TABLE `image` (
  `image` blob
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2 个答案:

答案 0 :(得分:2)

立即解决方法是将第37行更改为:

mysqli_query($con,"INSERT INTO image (image) VALUES (\"{$_FILES['file']['tmp_name']}\") ");

但是,您仍未存储文件内容,而是存储tmp_name。此链接提供了有关如何在数据库中存储图像的一些信息:http://kennykee.com/92/saving-image-to-database-using-php/

或者:http://forum.codecall.net/topic/40286-tutorial-storing-images-in-mysql-with-php/

或者只是在Google上搜索&#34; php将图像存储在mysql数据库中&#34;

答案 1 :(得分:2)

以下是首选使用mysqli

执行此操作的方法
$stmt = $con->prepare('INSERT INTO image (image) VALUES (?)');

$null = null;
$stmt->bind_param('b', $null);
$stmt->send_long_data(0, file_get_contents($_FILES['file']['tmp_name']));

$stmt->execute();