简体   繁体   中英

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. id, name and image, with image set as 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 is a MySQL reserved word

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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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