Dikshant Ghimire
Dikshant Ghimire

Reputation: 85

how to add many images to a mysql database?

i have a form which is able to upload multiple selected files to the folder. I just need to find how how to insert them into the database using PHP?

HTML form

<form name="demoFiler" id="demoFiler" enctype="multipart/form-data">
<input type="file" name="multiUpload" id="multiUpload" multiple />
<input type="submit" name="submitHandler" id="submitHandler" value="Upload" class="buttonUpload" />
</form>

PHP code

if($_SERVER['REQUEST_METHOD'] == "POST"){
    if(move_uploaded_file($_FILES['file']['tmp_name'], "uploads/".$_FILES['file']['name'])){
        echo($_POST['index']);
    }
    exit;
}

This is my code and first of all I can't get the files to be moved to the upload folder:

<?php

$username = "root";
$password = "";
$host = "localhost";
$database = "db_holiday";

// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

// Select your database
mysql_select_db ($database);

if($_SERVER['REQUEST_METHOD']=="POST")
{
    foreach ($_FILES['multiUpload']['name'] as $fileName) { 
        $uploaddir= '/upload/';
    $uploadfile = $uploaddir . basename($fileName);
        if (move_uploaded_file($fileName, $uploadfile)) {
            echo "File is valid, and was successfully uploaded.\n";
        } else {
            echo "Possible file upload attack!\n";
        }
    }
}

?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="multiUpload[]" id="multiUpload" multiple="multiple" />
<input type="submit" name="button"/>
</form>

Upvotes: 3

Views: 2018

Answers (2)

vusan
vusan

Reputation: 5331

HTML:

<input type="file" name="multiUpload[]" id="multiUpload" multiple />

php:

foreach ($_FILES['multiUpload'] as $fileName) { 
    //write your code here
    //$fileName
}

Upvotes: 4

Mr. Alien
Mr. Alien

Reputation: 157334

Use 2 input type="file" elements

<input type="file" name="img_1" />
<input type="file" name="img_2" />

Access each file using

$_FILES['img_1'][];
$_FILES['img_2'][];

Or you can also use an array like

<input type="file" name="img[]" />
<input type="file" name="img[]" />
<!--Which is often used in checkboxes-->

And access each image using

$_FILES['img']['tmp_name'][0];
$_FILES['img']['tmp_name'][1];

Upvotes: 0

Related Questions