save image in folder and path in mysql database

2019-06-12 16:22发布

问题:

I have a form like this:

<form method="post" enctype="multipart/form-data">
 <input type="text" id="title" placeholder="Project Title"/><br />
 <input type="text" id="vurl" placeholder="If You have any video about project write your video url path here" style="width:435px;"/><br />
<textarea id="prjdesc" name="prjdesc" rows="20" cols="80" style="border-style:groove;box-shadow: 10px 10px 10px 10px #888888;"placeholder="Please describe Your Project"></textarea>

<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br>
<input type="button" name="submit" value="Submit" id="update"/>
</form>

On click submit the data is storing in database and displaying using Ajax call this is my js code:

$("#update").click(function(e) {
      alert("update");
      e.preventDefault();
      var ttle = $("#title").val();
      alert(ttle);
      var text = $("#prjdesc").val(); 
      var vurl = $("#vurl").val();
      var img = $("#file").val();
      alert(vurl);
      var dataString = 'param='+text+'&param1='+vurl+'&param2='+ttle+'&param3='+img;
      $.ajax({
        type:'POST',
        data:dataString,
        url:'insert.php',
        success:function(id) {
          alert(id);
          window.location ="another.php?id="+id;;
        }
      });
    });

here i am storing data using insert.php and displaying using another.php but when coming to the image part i dont understand how to store image in folder and path in db, i mean i am bit confused to integrate code in insert.php

insert.php

$host="localhost";
$username="root";
$password="";
$db_name="geny";
$tbl_name="project_details";


mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

 $name = $_POST['param'];
 $video = $_POST['param1'];
 $title = $_POST['param2'];
 $sql="INSERT INTO $tbl_name (title, content, video_url) VALUES ('$title','$name','$video')";

 if(mysql_query($sql)) {
echo mysql_insert_id();

 } else {
  echo "Cannot Insert";
 }

if i do separate then the image is storing in folder..

if i do separate then the form code is:

    <form action="upload_file.php" method="post"
  enctype="multipart/form-data">
    <label for="file">Filename:</label>
     <input type="file" name="file" id="file"><br>
     <input type="submit" name="submit" value="Submit">
     </form>

upload_file.php:

<?php
 $allowedExts = array("gif", "jpeg", "jpg", "png");
 $extension = end(explode(".", $_FILES["file"]["name"]));
 if ((($_FILES["file"]["type"] == "image/gif")
 || ($_FILES["file"]["type"] == "image/jpeg")
 || ($_FILES["file"]["type"] == "image/jpg")
 || ($_FILES["file"]["type"] == "image/pjpeg")
 || ($_FILES["file"]["type"] == "image/x-png")
 || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 50000)
    && in_array($extension, $allowedExts))
  {
 if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
 else
{
   echo "Upload: " . $_FILES["file"]["name"] . "<br>";
   echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

if (file_exists("C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]))
  {
  echo $_FILES["file"]["name"] . " already exists. ";
  }
else
  {
  move_uploaded_file($_FILES["file"]["tmp_name"],
  "C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]);
 // echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
  $tmp = "C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"];
  echo $tmp;
  }
  }
}
else
 {
 echo "Invalid file";
 }
?>

this is working perfectly...

my question is how to integrate this code in insert.php... please help me...

回答1:

This code would work fine without the use of javascript. But make sure to change the directory and the table name and fields on line "2" and "66" resp.

We will create a hidden textarea which will create the datastring and we will get all the params using $_GET

<script>
$("#update").click(function(e) {
  alert("update");
  e.preventDefault();
  var ttle = $("#title").val();
  alert(ttle);
  var text = $("#prjdesc").val(); 
  var vurl = $("#vurl").val();
  var img = $("#file").val();
  alert(vurl);
  var textareastring = $('#string').val();
  var dataString = 'textareastring' = textareastring;
  $.ajax({
    type:'POST',
    data:dataString,
    url:'insert.php?param='+text+'&param1='+vurl+'&param2='+ttle+'&param3='+img',
    success:function(id) {
      alert(id);
      window.location ="another.php?id="+id;;
    }
  });
});
</script>
<textarea id="string" style="display:none;">aa</textarea>
<?php
$name = $_GET['param3']; 
// The name.n ow replacing all the $file_name with $name
$url = $_GET['param1'];
$text = $_GET['param'];
$title = $_GET['param2'];
$upload_dir = $url;
$num_files = 1;
//the file size in bytes.
$size_bytes =104857600; //51200 bytes = 50KB.
//Extensions you want files uploaded limited to.
$limitedext = array(".tif",".gif",".png",".jpeg",".jpg");
//check if the directory exists or not.
if (!is_dir("$upload_dir")) {
  die ("Error: The directory <b>($upload_dir)</b> doesn't exist.  ");
}
//check if the directory is writable.
if (!is_writeable("$upload_dir")){
  die ("Error: The directory <b>($upload_dir)</b> .  ");
}
if (isset($_POST['upload_form'])){

   echo "<h3>Upload results:</h3><br>";

   //do a loop for uploading files based on ($num_files) number of files.
   for ($i = 1; $i <= $num_files; $i++) {

       //define variables to hold the values.
       $new_file = $_FILES['file'.$i];
       $name = $new_file['name'];
       //to remove spaces from file name we have to replace it with "_".
       $name = str_replace(' ', '_', $name);
       $file_tmp = $new_file['tmp_name'];
       $file_size = $new_file['size'];

       #-----------------------------------------------------------#
       # this code will check if the files was selected or not.    #
       #-----------------------------------------------------------#

       if (!is_uploaded_file($file_tmp)) {
          //print error message and file number.
          echo "File: Not selected.<br><br>";
       }else{
             #-----------------------------------------------------------#
             # this code will check file extension                       #
             #-----------------------------------------------------------#

             $ext = strrchr($name,'.');
             if (!in_array(strtolower($ext),$limitedext)) {
                echo "File $i: ($name) Wrong file extension.  <br><br>";
             }else{
                   #-----------------------------------------------------------#
                   # this code will check file size is correct                 #
                   #-----------------------------------------------------------#

                   if ($file_size > $size_bytes){
   echo "File : ($name) Faild to upload. File must be no larger than <b>100   MB</b> in size.";
                   }else{
                #-----------------------------------------------------------#
                # this code check if file is Already EXISTS.                #
                #-----------------------------------------------------------#
                         if(file_exists($upload_dir.$name)){
                             echo "File: ($name) already exists.    <br><br>";
                         }else{
                               #-------------------------------#
                               # this function will upload the files.         #
                               #-------------------------------#
                               if     (move_uploaded_file($file_tmp,$upload_dir.$name)) {
                                   $sql = "INSERT INTO table_name(field1, field2) VALUES('$field1', '$field2');";
                                   echo "File: ($name) has been uploaded successfully." . "<img src='uploads/$name'/>";  

                               }else{
                                    echo "File: Faild to upload.  <br><br>";
                               }#end of (move_uploaded_file).

                         }#end of (file_exists).

                   }#end of (file_size).

             }#end of (limitedext).

       }#end of (!is_uploaded_file).

   }#end of (for loop).
   # print back button.
 ////////////////////////////////////////////////////////////////////////////////
 //else if the form didn't submitted then show it.
}else{
echo "<form method=\"post\" action=\"$_SERVER[PHP_SELF]\" enctype=\"multipart/form-        data\">";
       // show the file input field based on($num_files).
       for ($i = 1; $i <= $num_files; $i++) {
           echo "<b>Image: </b><input type=\"file\" size=\"70\"             name=\"file". $i ."\" style=\"width:45%\">";
       }
echo " <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$size_bytes\">
       <input type=\"submit\" name=\"upload_form\" value=\"Upload\">
       </form>";
}
?>


回答2:

Take reference from this link how to upload image using ajax. It will help you.

http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html



回答3:

...You can check this code mentioned in this article , (http://jagdeepmalhi.blogspot.ru/2011/02/phpmysql-store-file-path-in-database.html) It has sample code, and don't forget to read the comments about it, if something goes wrong !.



回答4:

If you mean how to call insert.php after submit button was clicked, in this line

<form method="post" enctype="multipart/form-data">

you have to add this

<form method="post" enctype="multipart/form-data" action="insert.php">


回答5:

<?php

/*dont use path like this C:/wamp/www/WebsiteTemplate4/upload/ becuase you are working at localhost server*/
if (file_exists("upload/" . $_FILES["file"]["name"])){

    echo $_FILES["file"]["name"] . " already exists. ";

}else{

    $file = $_FILES["file"]["name"]
    $filePath = "upload/" . $file;
    if(move_uploaded_file($_FILES["file"]["tmp_name"], $filePath)){

        /*prepare sql query here and insert*/
        $sql = "INSERT INTO table_name(field1, field2) VALUES('$field1', '$field2');";
        if(mysql_query($sql)){

            echo "File saved in database successfully <strong>{$filePath}</strong>";

        }else{

            echo "File not uploaded there are an error <strong>{$filePath}</strong>";

        }


    }else{

        echo "File not uploaded there are an error <strong>{$file}</strong>";

    }


} ?>

try this code if you have any doubt or code not working fine then ask me again. Thanks