phprockers-logo

Dynamic upload the multiple files in php with Javascript validation

<?php
    $con = mysql_connection() or (mysql_error();
    mysql_db_select("phprockers", $con) or mysql_error();
?>
<html>
<script type="text/javascript" >
    function add_more() {
        var img = document.getElementById("image").value;
        img=parseInt(img)+1;
        var txt = "<br><input type = file name = images"+img+">";
        document.getElementById("image").value=img;
        document.getElementById("files").innerHTML += txt;
    }


    function validate(){
        var img = document.getElementById("image").value;
        img=parseInt(img);

        while(img > 0){
            var x=document.forms["myForm"]["images"+img].value
            if (x=="") {
            alert("please select file");
            return false;
            }
            img--;
        }  
    }
</script>
<body>
    <form method="POST"  name="myForm" action="" enctype="multipart/form-data" onSubmit="return validate();">
    <div id="files">  <input type="file" name='images1'/><br></div>
    <input type="hidden" value=1 id="image" name="image"/>
    <input type = "submit" name = "submit" value = "Submit"  />
    <div style="cursor:pointer" onClick="add_more();">Attach File</div>
    </form>
    <?php
    if($_POST['submit']!="" ) {
        $upload_directory = 'upload/';
        for ($i = 1; $i <= $_REQUEST['image']; $i++) {
            $path=$_FILES['images'.$i]['name'];
            move_uploaded_file ($_FILES['images'.$i]['tmp_name'], $upload_directory . $_FILES['images'.$i]['name']);
            $query="INSERT INTO `browsefile`(`id`, `path`) VALUES (NULL,'$path')";
            mysql_query( $query );
        }      
    }
    ?>
</body>
</html>

1 comment:

  1. If we select one file and then click on Attach File the selected file will clear.

    ReplyDelete