0

I need to upload 5 images at ones with they labels I have made this before to upload many images at one it works fine but I need to have an label for each image how this can be done

take a look at my code.

this is the HTML code

<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data">
  <?php if(isset($_GET['msg'])){$msg=$_GET['msg']; echo $msg;} ?>
  <span style="font-weight: bold; color: #F00;">*ملحوظة </span>الصورة الأولي التي سترفع ستكون صورة المشروع الأساسية نرجوا أختيارها بعناية

  <p><label for="img1">صورة 1</label>
  <input type="file" name="img[]" id="fileField1" />
  <input type="text" name="Limage1" id="Limage1" placeholder="Add label">
  </p>

  <p><label for="img2">صورة 2</label>
  <input type="file" name="img[]" id="fileField2" />
  <input type="text" name="Limage2" id="Limage2" placeholder="Add label">
  </p>

  <p><label for="img3">صورة 3</label>
  <input type="file" name="img[]" id="fileField3" />
  <input type="text" name="Limage3" id="Limage3" placeholder="Add label">
  </p>

  <p><label for="img4">صورة 4</label>
  <input type="file" name="img[]" id="fileField4" />
  <input type="text" name="Limage4" id="Limage4" placeholder="Add label">
  </p>

  <p><label for="img5">صورة 5</label>
  <input type="file" name="img[]" id="fileField5" />
  <input type="text" name="Limage5" id="Limage5" placeholder="Add label">
  </p>

 <p><input type="submit" name="submitCon" id="submitCon" value="Upload More Images">
 <input type="submit" name="submit" id="submit" value="I am Finished"></p>
</form>

and this is my php for uploading the images

<?php
if(isset($_POST['submit'])){

$target = '../images/Projects/';
    $num=1;
    $projectID=$p;
    foreach ($_FILES["img"]["error"] as $key => $error)
    {
        if ($error==UPLOAD_ERR_OK) 
        {
            $tmp_name = $_FILES["img"]["tmp_name"][$key];
            $name = $_FILES["img"]["name"][$key];
            move_uploaded_file($tmp_name, "$target/$name");

            $putData = "INSERT INTO projects_images (id, image, image_id)VALUE('', '$name', '$projectID')";
            $result = $db->query($putData)or die($db->error);
            if($result){
                header('Location:includes/pan/projects/google/face.php?propid='.$p);
                }else{
                echo"Error";
            }
        }
    } 
}

as shown in the HTML code I have a file to upload images and I have a label for each image which I'd like add

how can I do that?

4
Contributors
7
Replies
42
Views
3 Years
Discussion Span
Last Post by m1k3.mca
2

your html

<p><label for="img1">صورة 1</label>
<input type="file" name="img[]" id="fileField1" />
<input type="text" name="label[]" id="Limage1" placeholder="Add label">
</p>

your php

...
$tmp_name = $_FILES["img"]["tmp_name"][$key];
$name = $_FILES["img"]["name"][$key];

$label = $_POST['label'][$key];

....
// change your query to save $label in your db

if($result){
    // header('Location:includes/pan/projects/google/face.php?propid='.$p);
    // cant redirect, have to do 4 more images
}else{
echo"Error";
}
...
1

I have an "old" bit of code, slightly rejigged that you may find useful. Not intended to be a tailor-made solution, but I tested it and it seems to work OK.
The php

<?php
//CHECK TO SEE IF FORM SENT
if($_POST) {
    //reArrayFiles from http://www.php.net/manual/en/features.file-upload.multiple.php#53240
    function reArrayFiles($file_post) {
        $file_ary = array();
        $file_count = count($file_post['name']);
        $file_keys = array_keys($file_post);
        for ($i=0; $i<$file_count; $i++) {
            foreach ($file_keys as $key) {
                $file_ary[$i][$key] = $file_post[$key][$i];
            }
        }
        return $file_ary;
    }

    //Sometimes lines may be skipped, eg user fills boxes 0,2,3
    //So function to filter out empty file array items 
    function pullEmptyFiles($item) {
        return $item['error'] == 0;     
    }
    //If labels exist and no file OR vice-versa let know (problem returns true) 
    function checkWrongKeys($labels, $files) {
        return array_diff_key($files,$labels) || array_diff_key($labels,$files);
    }

    //Create succinct $files array without empty items
    $raw_files = reArrayFiles($_FILES['img']);
    $files = array_filter($raw_files, "pullEmptyFiles");    
    //Create $labels array without empty items - should match array indexes for $files
    $labels = array_filter($labels);
    //Check array indexes are the same 
    if(checkWrongKeys($labels,$files)) {
        echo "Labels and images do not match";
    //Check there are actual files to upload    
    }elseif(count($files) == 0){
        echo "No files uploaded";
    //OK arrived here - let's upload and write to DB    
    } else {
        //empty arrays to store data
        $sql = array();
        $bind = array();
        foreach($files as $key=>$file) {
            $tmpname = $file['tmp_name'];
            $filename = $file['name'];
            //change directory 'ups/' to yours
            if(move_uploaded_file($tmpname, 'ups/' . $filename)) {
                $sql[] = "(?, ?)";
                $bind[] = $labels[$key];
                $bind[] = $filename;
            }
        }
        $sql_string = "INSERT INTO images (`label`, `image`) VALUES " . implode(",",$sql);
        //echo $sql_string;
        $dsn = 'mysql:dbname=daniweb;host=localhost';
        $user = 'root';
        $password = '';
        try {
            $dbh = new PDO($dsn, $user, $password);
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
        //RUN QUERY and BIND PARAMS
        $stmt = $dbh->prepare($sql_string);
        $stmt->execute($bind);

        //You should check to see if this can been successfully written to DB               
    }
}
?>

The HTML

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" enctype="multipart/form-data" >
    <input name="label[]" /><input type="file" name="img[]" /><br />
    <input name="label[]" /><input type="file" name="img[]" /><br />
    <input name="label[]" /><input type="file" name="img[]" /><br />
    <input name="label[]" /><input type="file" name="img[]" /><br />
    <input name="label[]" /><input type="file" name="img[]" /><br />
    <input type="submit" name="submit" value="UPLOAD" />
</form>

</div>      
</div>
</body>
</html>
0

well though its done to death,but the news is???this code is not storing the images (i have changed the database name from daniweb to "mydb",n insert into "mytable",n guess what,this code is not even showing successful upload.

0

well though its done to death,but the news is???

You're cross-posting. Please keep it to the thread concerned. Anyway...

If you don't show where it's going wrong, it's difficult to help you. It works fine for john_ef and myself, so perhaps you've neglected to change a couple of parameters or your SQL table is not the same as ours.

Caveat
As I mentioned in the snippet, this is not meant to be a complete solution for every use case, just a bit of code to play with.

0
Table structure for table `album`
--

CREATE TABLE IF NOT EXISTS `album` (
  `name` varchar(20) NOT NULL,
  `userid` varchar(50) NOT NULL,
  `data` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Dumping data for table `album`
--

INSERT INTO `album` (`name`, `userid`, `data`) VALUES
('pix', 'prandeep', '2014-03-20'),
('rock', 'prandeep', '2014-03-20');

Table structure for table `image`
--

CREATE TABLE IF NOT EXISTS `image` (
  `name` varchar(50) NOT NULL,
  `imgnm` varchar(50) NOT NULL,
  `userid` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

now my entire code lies here.

<html>
<body>
<form action="albumsuc.php" method="post">
Album Name<input type=text name=n1><br>
<input type=submit value=submit>
</form>
</body>
</html>//create album page
<?php//create albumsuccess code
    session_start();
    include "connect.php";
?>
<?php
    $dt=Date('Y-m-d');
    @$userid=$_SESSION['userid'];
    @$q="insert into album values('".$_POST['n1']."','".$_SESSION['userid']."','".$dt."')";
    $s=mysql_query($q);
    if($s>0)
        echo "<h1>Create Sucessfully";
    mysql_close();
?>
<a href="existantalbum.html">Upload Photo</a>
form action="$PHP_SELF.php" method="post">//insert into album created
Insert Into Album-Name<input type=text name=n1>
<input type=submit value=submit>
</form></div>
<html>//image upload into album created page
<body>
<form action="imgupsuc.php" method="post" enctype="multipart/form-data">
<?php
    @$nm=$_POST['n1'];
?>
<input type=hidden name=n1  value=<?php echo $nm ?>>
Select a picture<input type="file" name="file" size="50">
<input type="submit" value="upload">

</form>
</body>
</html>
    <?php//image upload successfull php code
session_start();
    include "connect.php";
?>
<?php
    $name=$_POST['n1'];
    move_uploaded_file($_FILES['file']['tmp_name'],"./pic/".$_SESSION['userid']."".$_FILES['file']['name']);
    $q="insert into image values('".$name."','".$_SESSION['userid']."".$_FILES['file']['name']."','".$_SESSION['userid']."')";
    $s=mysql_query($q);
    if($s>0)
        echo "<h1> pic insert successfully";
    mysql_close();
?><li>Go Back to Choose another photo to upload</li><b>or</b>
<a href="view.php">View Album</a>Or <a href="fileup.php"> Upload Another Image</a>
<?php
    session_start();
    include "connect.php";
?>
<?php
    $nm=$_GET['name'];
    $q="select * from image where name='".$nm."' and userid='".$_SESSION['userid']."'" ;
    $s=mysql_query($q);
    $count=0;
    while($r=mysql_fetch_array($s)){
        $img=$r['imgnm'];
        if($count==8){
?>
        <br><hr>
<?php
        $count=0;
        }
?>      
        <input type="checkbox" name="image" value="<?php echo $img ?>"><img src="./pic/<?php echo $img ?>" height=100 width=100>
<?php
        $count=$count+1;
    }
?>
                </section>
                <aside>
                        <section class="new-offers">
                            <h5>Fill Up the details for Ordering</h5>

                            <fieldset><form action='order.php' method='POST'><legend>Order DEtails</legend>
                                        <div>
                                            <label for="name" class="title">Passport:</label>
                                            <input type="text" id="passport" name="pp" size="5"/>
                                        </div>
                                        <div>
                                            <label for="stamp" class="title">Stamp-Size:-</label>
                                            <input type="text" id="stamp" name="stamp" size="5" /></div>
                                            <div>
                                            <label for="poster" class="title">Poster-Size:-</label>
                                            <input type="text" id="poster" name="poster" size="5" /></div>

                                            <input type="submit" value="Order Now"
                                            id="submit" />
                            </fieldset></form>//viewing the images in respective albums

okay so here we go,my entire mysql table for "album" and "image" table is above.i can now successfully create albums and upload images in respective albums.my problem lies here.In the code fileup.php i want to put 5 file upload input types so that i can upload atleast 5 images at a time in my selected album(through existantalbum.html)i used your code and made the necessary adjustments.but it din't work.So if possible then check out my code and suggest me how i can upload atleast 5 images into an album at a time. thank you :)

0

Sorry, you say you used my code, but I don't recognise the code you provide. Am busy today, so I won't be able to help. Anybody else?

0

"Sorry, you say you used my code, but I don't recognise the code you provide. Am busy today, so I won't be able to help. Anybody else?"

thanx for your concern :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.