简体   繁体   English

PHP的使用PDO上传图像到MySQL数据库?

[英]PHP Upload image to mysql database using PDO?

I have a database set up and am trying to upload an image to it. 我已经建立了一个数据库,正在尝试将图像上传到该数据库。 The database is called 'blob' and has 3 fields. 该数据库称为“ blob”,具有3个字段。 id, name and image, with image set as blob. ID,名称和图片,图片设置为Blob。 When trying to upload the image i get an error that i am unsure of. 尝试上传图片时,出现不确定的错误。 Below is my code. 下面是我的代码。

<?php
include ("dbConnect.php");
?>

<form action="imageuploadtest.php" enctype="multipart/form-data" method="post">
<input name="image" type="file"><input name="submit" type="submit" value="Upload">
</form>

<?php 

if(isset($_POST['submit']))
{

  $imageName = $_FILES["image"]["name"];
  $imageData = file_get_contents($_FILES["image"]["tmp_name"]);
  $imageType = $_FILES["image"]["type"];

  if(substr($imageType,0,5)=="image")
  {
     $dbQuery = $db->prepare("INSERT INTO blob ( name, image) VALUES ('$imageName', '$imageData')");
     $dbQuery->execute();
  }
  else
  {
   echo "only images are allowed";
  } 
}
?>

The database connection is fine, but i get the following error message that i am usure of how to fix. 数据库连接很好,但是我收到以下错误消息,说明我很确定如何修复。

 Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters' in N:\ftp\compc\d12ac1\FlightsFromNI\imageuploadtest.php:23 Stack trace: #0 N:\ftp\compc\d12ac1\FlightsFromNI\imageuploadtest.php(23): PDO->prepare('INSERT INTO blo...') #1 {main} thrown in N:\ftp\compc\d12ac1\FlightsFromNI\imageuploadtest.php on line 23.

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

EDIT: Have now changed my table name from blob to imgupload but still get the same error message? 编辑:现在已经将我的表名从Blob更改为imgupload,但仍然收到相同的错误消息?

blob is a MySQL reserved word blob是MySQL的保留字

Either rename your table to something else, or use ticks around it: 将您的表重命名为其他名称,或在表周围打勾:

INSERT INTO `blob` ...

Nota: It's usually best to store files in folders and make a reference to the file, rather than storing binary data in a table. 注意:通常最好将文件存储在文件夹中并对其进行引用,而不是将二进制数据存储在表中。 This will eventually dramatically increase your database size. 这最终将极大地增加您的数据库大小。

It's not about blob. 这与blob无关。 It's about binary data. 关于二进制数据。 Try to use that line (but it may also not work): 尝试使用该行(但也可能不起作用):

$db->prepare("INSERT INTO blob ( name, image) VALUES ('$imageName', " . $db->quote($imageData) . ")");

Also your query is not SAFE (for hackers), you should be sanitizing all input to your database. 同样,您的查询不是安全的(针对黑客),您应该清除数据库中的所有输入。 PDO has great support for prepared statements . PDO对准备好的语句有很大的支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM