0

I am inserting input form into two different tables. the first table is for the information, and the other table is for images of the information.

When I submit the information, I would like to upload multiple images per a row of the first table in separate table, and also insert last_insert_id to each images into the second table.

table1
location ID | address | contact information 

table2
pictureID | location ID | filepath 

With the following code, it only inserts one image, but it uploads all the images into the folder.

<?php 

    include_once 'dbconnect.php';
    mysql_query("SET NAMES UTF8");
    session_start();
    $tbl_name="location";
    $tbl_image="image";

    if(isset($_POST['btn-upload'])){

        $name2=$_POST['name2'];
        $phone=$_POST['phone'];
        $email=$_POST['email'];
        $type=$_POST['type'];
        $other=$_POST['other'];
        $description=$_POST['description'];
        $address=$_POST['address'];
        $name=$_POST['name'];
        $lat=$_POST['lat'];
        $lng=$_POST['lng'];
        $country=$_POST['country'];
        $administrative_area_level_1=$_POST['administrative_area_level_1'];
        $place_id=$_POST['place_id'];
        $url=$_POST['url'];
        $website=$_POST['website'];




    $sql="INSERT INTO $tbl_name(name2, phone, email, type, other, description, address, name, lat, lng, country, administrative_area_level_1, place_id, url, website) VALUES ('$name2', '$phone', '$email', '$type','$other', '$description', '$address', '$name', '$lat', '$lng', '$country', '$administrative_area_level_1', '$place_id', '$url', '$website')";
    $result=mysql_query($sql);

        for($i=0; $i<count($_FILES['image']['tmp_name']); $i++)
        {
            $file = rand(1000,100000)."-".$_FILES['image']['name'][$i];
            $file_loc = $_FILES['image']['tmp_name'][$i];
            $file_size = $_FILES['image']['size'][$i];
            $file_type = $_FILES['image']['type'][$i];
            $folder="uploads/";

            // new file size in KB
            $new_size = $file_size/1024;  
            // new file size in KB

            // make file name in lower case
            $new_file_name = strtolower($file);
            // make file name in lower case

            $final_file=str_replace(' ','-',$new_file_name);
            $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
            $userRow=mysql_fetch_array($res);
            $userID=$userRow['userID'];

            if(move_uploaded_file($file_loc,$folder.$final_file))
            {
                $sql="INSERT INTO $tbl_image(user_ID, Location_ID, file) VALUES('$userID', LAST_INSERT_ID(), '$final_file')";
                mysql_query($sql);
                ?>
                <script>
                alert('successfully uploaded');
                window.location.href='index.php?success';
                </script>
                <?php
            }
            else
            {
                ?>
                <script>
                alert('error while uploading file');
                window.location.href='index.php?fail';
                </script>
                <?php
            }

        }

        if($result){
        echo "Successful";
        echo "<BR>";
        echo "<a href='index.php'>Back to main page</a>";
        }

        else {
        echo "ERROR";
        }

        if($result1){
        echo "Upload Successful";
        echo "<BR>";
        echo "<a href='locationform.php'>Back to main page</a>";
        }

        else {
        echo "ERROR";
        }


    }   




?> 

<?php 
// close connection 
mysql_close();
?>
4
  • Your code is right but after first successful image table insertion you are redirecting code. so you get only one insert in image table. Commented Apr 16, 2017 at 5:46
  • 1
    As mysql_* was deprecated in PHP 5.5 (please refer to PHP doc) you should really consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection. NEVER trust user's data! And please use error_reporting(E_ALL); ini_set('display_errors', 1); on top of your pages and let us know if any error is thrown Commented Apr 16, 2017 at 5:58
  • Moreover, you should not assume that your sql calls are successful. Add error handling after each of the sql queries and print out any error messages Commented Apr 16, 2017 at 5:59
  • then how do I not to redirect the code? Commented Apr 16, 2017 at 6:27

3 Answers 3

0
$b=$pdo->prepare(" INSERT INTO `table1` SET `address`=:address, `contact`=:contact ");
$b->bindParam(":address",$address);
$b->bindParam(":contact",$contact);
$b->execute();
$LastId = $pdo->lastInsertId();

if($LastId > 0){
    $b=$pdo->prepare(" INSERT INTO `table2` SET `pictureID`=:pictureID, `filepath`=:filepath ");
    $b->bindParam(":pictureID",$LastId);
    $b->bindParam(":filepath",$filepath);
    $b->execute();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Figured it out at last. It was the last_insert_ID that had a problem. Last_instert_ID had to be stated outside the For loop.

$locationID=mysql_insert_id($conn);

Above is added right below the first insert query.

$sql="INSERT INTO $tbl_location(name2, phone, email, type, other, description, address, name, lat, lng, country, administrative_area_level_1, place_id, url, website) 
    VALUES ('$name2', '$phone', '$email', '$type','$other', '$description', '$address', '$name', '$lat', '$lng', '$country', '$administrative_area_level_1', '$place_id', '$url', '$website')";
    $result=mysql_query($sql);

    $locationID=mysql_insert_id($conn);

    for($i=0; $i<count($_FILES['image']['name']); $i++)
    {
        $file = rand(1000,100000)."-".$_FILES['image']['name'][$i];
        $file_loc = $_FILES['image']['tmp_name'][$i];
        $file_size = $_FILES['image']['size'][$i];
        $file_type = $_FILES['image']['type'][$i];
        $folder="uploads/";

        // new file size in KB
        $new_size = $file_size/1024;  
        // new file size in KB

        // make file name in lower case
        $new_file_name = strtolower($file);
        // make file name in lower case

        $final_file=str_replace(' ','-',$new_file_name);
        $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
        $userRow=mysql_fetch_array($res);
        $userID=$userRow['userID'];


        if(move_uploaded_file($file_loc,$folder.$final_file))
        {
            $sql2="INSERT INTO $tbl_image(user_ID, Location_ID, file) VALUES('$userID', '$locationID', '$final_file')";
            $result = mysql_query($sql2);
            ?>
            <script>
            alert('successfully uploaded');
            window.location.href='index.php?success';
            </script>
            <?php
        }
        else
        {
            ?>
            <script>
            alert('error while uploading file');
            window.location.href='index.php?fail';
            </script>
            <?php
        }

    }

Comments

-2

// how to upload multiple image in database but image save in folder with upload table with last insert id with loop //


table1  - table1
ID | field1 | field2 

table2  - upload
pictureID | ID | uploadimage 


<?php

include("config.php");


if(isset($_POST['submit'])){
$field1 =$_POST['field1'];
$field2 =$_POST['field2'];
	 
$sql=mysql_query("INSERT INTO table1(field1,field2) VALUES ('field1','field2')"); // insert  record table 1



if($sql){
 $last = mysql_insert_id();   }	
if(isset($_FILES['uploadimage']['name']))  // uploadimage  file name and table column name same used here
{
    $file_name_all="";
    for($i=0; $i<count($_FILES['uploadimage']['name']); $i++) 
    {
        $tmpFilePath = $_FILES['uploadimage']['tmp_name'][$i];    
        if ($tmpFilePath != "")
        {    
           $path = "uploadimages/"; // create folder name
           $name = $_FILES['uploadimage']['name'][$i];
           $size = $_FILES['uploadimage']['size'][$i];

           list($txt, $ext) = explode(".", $name);
           $file= time().substr(str_replace(" ", "_", $txt), 0);
           $info = pathinfo($file);
           $filename ='image'. $file.".".$ext;
       }
	   if(move_uploaded_file($_FILES['uploadimage']['tmp_name'][$i], $path.$filename)) 
           { 
             $sql_image=mysql_query("insert into upload(ID,uploadimage) values('".$last."','".$filename."')"); //insert record table 2(upload)

           }
	   }
	  
}
}
?>
<form method="post" enctype="multipart/form-data">
<label>field - 1</label><input type="text" name="field1">
<label>field - 2</label><input type="text" name="field2">
<label>mutiple image upload</label> <input id="uploadimage" type="file" name="uploadimage[]" multiple accept="image/*" />
<button type="submit" name="submit">submit</button>
  </form>

1 Comment

You need to explain your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.