简体   繁体   中英

How to insert multiple rows and files into mysql using php array?

How to insert multiple rows and upload files into mysql database using php array?

I want to add a 'Add More' Option in this form by which the same fields got duplicates down to it, and can easily insert multiple rows as well as file uploads to mysql database.

Here is the code :

<?php

// @author - Chetanaya Aggarwal

?> 
<?php include('header_dashboard.php'); ?>
<?php include('session.php'); ?>
<?php $get_id = $_GET['id']; ?>
     <body id="home">
        <?php include('navbar_client.php'); ?>
        <div class="container-fluid">
            <div class="row-fluid">
                <?php include('Device_sidebar.php'); ?>

                        <div class="span9" id="content">
                            <div class="row-fluid">

                                <!-- block -->
                                <div class="block">
                                    <div class="navbar navbar-inner block-header">
                                        <div class="muted pull-left">Upload Documents</div>
                                        <div class="muted pull-right"><a id="return" data-placement="left" title="Click to Return" href="clients_list.php"><i class="icon-arrow-left icon-large"></i> Back</a></div>
                                        <script type="text/javascript">
                                        $(document).ready(function(){
                                        $('#return').tooltip('show');
                                        $('#return').tooltip('hide');
                                        });
                                        </script>                          
                                    </div>


                        <div class="block-content collapse in"> 
                         <div class="alert alert-success"><i class="icon-info-sign"></i> Please Fill in required details</div>                      
                            <form class="form-horizontal" method="post" enctype="multipart/form-data">                                                                              
                                        <table style width="100%">

                                        <tr>
                                <tr>
                                <td>
                                        <div class="control-group">
                                            <label class="control-label" style="font-size: 16px;" for="inputPassword"><b>Document Type</b></label>
                                            <div class="controls">
                                              <select name="docstype_id" class="chzn-select"  required/>
                                                 <option></option>
                                                 <?php $docs_type=mysql_query("select * from docs_type")or die(mysql_error()); 
                                                 while ($row=mysql_fetch_array($docs_type)){                                                
                                                 ?>
                                                 <option value="<?php echo $row['docstype_id']; ?>&nbspName&nbsp<?php echo $row['docsname']; ?>"><?php echo $row['docsname']; ?></option>
                                                 <?php } ?>
                                               </select>
                                             </div>
                                        </div>
                                </td>
                                <td>    
                                        <div class="control-group">
                                            <label class="control-label" style="font-size: 16px;" for="inputPassword"><b>Document Copy</b></label>
                                            <div class="controls">
                                            <input name="Photo" class="input-file uniform_on" id="fileInput" type="file" required>
                                            </div>
                                        </div>
                                </td>   
                                </tr>

                                <tr>
                                <td>        
                                    <div class="control-group">
                                            <label class="control-label" style="font-size: 16px;" id="la-add-mob" for="inputPassword"><b>Document No.</b></label>
                                            <div class="controls">
                                            <input type="text" class="span8" name="file_no" id="file_no" placeholder="Document No.">
                                            </div>
                                        </div>
                                </td>
                                <td>    

                                </td>
                                </tr>
                                <tr>
                                <td>
                                <div class="control-group">
                                        <div class="controls">
                                        <button name="save" id="save" data-placement="right" title="Click here to Save your new data." class="btn btn-primary"><i class="icon-save"></i> Save</button>              
                                        </div>
                                        </div>
                                </td>       
                                </tr>       
                                        <script type="text/javascript">
                                        $(document).ready(function(){
                                        $('#save').tooltip('show');
                                        $('#save').tooltip('hide');
                                        });
                                        </script>

                                </tr>
                                </table>                                
                            </form>
                            </div>
                            </div>

                            <?php
$uploadDir1 = 'uploads/'; //Image Upload Folder

if (isset($_POST['save'])){
$docstype_id = $_POST['docstype_id'];
$fileno = $_POST['file_no'];

function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; }

$fileName1 = $_FILES['Photo']['name'];
$extension = getExtension($fileName1);
$extension = strtolower($extension);
$tmpName1  = $_FILES['Photo']['tmp_name'];
$fileSize1 = $_FILES['Photo']['size'];
$fileType1 = $_FILES['Photo']['type'];
$image_name= $fileno.'.'.$extension;
$filePath1 = $uploadDir1 . $image_name;
$result1 = move_uploaded_file($tmpName1, $filePath1);
if (!$result1) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
    $fileName1 = addslashes($fileName1);
    $filePath1 = addslashes($filePath1);
}

mysql_query("insert into upload (clients_id,docstype_id,file_no,file_path) values('$get_id','$docstype_id','$fileno','$filePath1')")or die(mysql_error());                                          
?>

<script>
window.location = "clients_list.php";
$.jGrowl("Documents Uploaded Successfully added", { header: 'Device add' });
</script>
<?php
}

?>

                                    </div>
                                </div>
                                <!-- /block -->
                            </div>
                        </div>
            </div>
        <?php include('footer.php'); ?>
        </div>
        <?php include('script.php'); ?>
    </body>

I created a sample upload for you so that you can start, this is just a simple file upload.

<!-- In your HTML -->
    <form method="post" enctype="multipart/form-data" accept-charset="UTF-8" id="submitForm">

      <div class="upload">
        <input type="file" id='id1' name="image1" accept=".doc, .docx, .jpg, .pdf" />
        <input type="file" id='id2' name="image2" accept=".doc, .docx, .jpg, .pdf" />

        <input type="submit" name="submit" value='Upload'  />
      </div>

    </form>

<?php

// PHP Handler
if(isset($_POST["submit"])){

    $files = upload($_FILES);


    var_dump($files);
}

// Create a function for this something like:
function upload($data)
{

    define('DS', DIRECTORY_SEPARATOR);
    define('ROOT', dirname(__FILE__));

    // Initialize the array
    $file = array();

    // Create the folder name
    $folder_name =  date('m-Y', time());

    // Date today
    $date_today = date('d', time());

    // Build the Upload directory
    $upload_directory = ROOT . DS . 'upload' . DS . $folder_name . DS . $date_today;

    // Check if the folder exist or not
    if(!file_exists(ROOT . DS . 'upload' . DS . $folder_name)){

        // Create the directory
        mkdir(ROOT . DS . 'upload' . DS . $folder_name, 0777);

        // Change the permission
        chmod(ROOT . DS . 'upload' . DS . $folder_name, 0777);
    }

    if(!file_exists($upload_directory)){

        // Create the directory
        mkdir($upload_directory, 0777);

        // Change the permission
        chmod($upload_directory, 0777);
    }

    foreach($data as $key => $value){

        // Check if the file name is empty
        if(!empty($value['name'])){

            // Get the file name
           $file_name = str_replace(" ", "_", strtoupper($value['name']));

          // Create the real file
          $real_file = date('ymd_His',time()) .'_'.$key.'_'. $file_name;

           if(!move_uploaded_file($value['tmp_name'], $upload_directory . DS . $real_file)) {

               // Change the file setting
                chmod($upload_directory . DS . $real_file, 0774);

            } //move_uploaded_file

            $ext            = explode(".", $value['name']);
            $file_ext   = array_pop($ext);

            $file[$key] = array(
                // Build the array needed to store in the database
                'file_path'         => '/upload/'.$folder_name."/".$date_today."/".$real_file,
                'file_name' => $value['name'],
                'file_type'     => $value['type'],
                'file_size'     => $value['size'],
                'file_ext'      => strtolower($file_ext),
                'upload_date'=> date("Y-m-d H:i:s"),
            ); // end array

        } //!empty
    }

    return $file;       

}

?>

Note: Put this in a test folder and create a folder "upload" inside it. Run the php file. The resulting $files is basically an array you can use to pass in your mysql query.

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