0

I'm trying to upload multiple images from a textbox to MYSQL database using PHP. But somehow it only inserts the last item from the array in the database.

I tried uploading using one image, and that worked.

What am I doing wrong?

form.php:

<form action="addpicture.php?id=<?php echo $prodID; ?>" method="POST" enctype="multipart/form-data">  
    <input type="file" name="image[]" multiple/>
    <input type="submit" value="upload" name="image" class="btn btn-primary" /> 
</form>

Addpicture.php:

    <?php
    session_start();
    include '../includes/config.php';

    $prodID = $_GET['id'];

    foreach(array_keys($_FILES['image']['error']) as $key){
    $temp_name = $_FILES['image']['tmp_name'][$key];
    $t_name = file_get_contents($temp_name);
    $t_name = mysql_real_escape_string($t_name);

    $insert = mysql_query("INSERT INTO tblpictures(prodID, foto) VALUES ('$prodID','$t_name')") or die(mysql_error());          

            header('location: form.php?prodID=' . $prodID);
            exit();
    }

    ?>

EDIT: SOLVED HTML 5 multi file upload with PHP

2
  • addslashes() is to SQL injection prevention as using a roll of toilet paper is to soaking up an ocean. Do NOT use it. You may think you're doing the right thing, but it's NOT a defense against sql injection in any real way. Commented May 15, 2013 at 21:19
  • Thanks. Now I get an sql 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 I don't know what could be wrong to my sql Commented May 15, 2013 at 21:24

1 Answer 1

0

You're using the PHP array-based naming for file uploads. PHP's treatment of that in the $_FILES array is BEYOND moronic.

Single files show up as

$_FILES = array(
   'fieldname' => array('error' => ..., 'name' => '...', etc....)
);

As soon as you go into array mode, you get a completely DIFFERENT structure:

$_FILES = array(
   'fieldname' => array (
       'error' => array(
            0 => 'error code of first file'
            1 => 'error code of second file'
            etc...
       )
       'name' => array(
            0 => 'first filename',
            1 => 'second filename',
            etc...
       )
   )
)

You need to loop on:

foreach(array_keys($_FILES['image']['error']) as $key) {
    $name = $_FILES['image']['name'][$key];
    $temp_name = $_FILES['image']['tmp_name'][$key];
}
Sign up to request clarification or add additional context in comments.

1 Comment

don't post code into a comment. editor your question and put it there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.