php 将图像保存在mysql数据库中的文件夹和路径中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16938113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:56:04  来源:igfitidea点击:

save image in folder and path in mysql database

phpfile-upload

提问by user2330772

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:

单击提交时,数据存储在数据库中并使用 Ajax 调用显示,这是我的 js 代码:

$("#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 存储数据并使用 another.php 显示但是当来到图像部分时我不明白如何将图像存储在文件夹和路径中的数据库中,我的意思是我有点困惑在 insert.php 中集成代码

insert.php

插入.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:

上传_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...

我的问题是如何将此代码集成到 insert.php 中...请帮帮我...

回答by lakshya_arora

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.

这段代码可以在不使用 javascript 的情况下正常工作。但请确保更改目录和表名以及“2”和“66”行上的字段。

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

我们将创建一个隐藏的文本区域,它将创建数据字符串,我们将使用 $_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>";
}
?>

回答by Neil patrick Ishiwata

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

如果您的意思是在单击提交按钮后如何调用 insert.php,请在此行中

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

you have to add this

你必须添加这个

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

回答by Satish

<?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

如果您有任何疑问或代码无法正常工作,请尝试使用此代码,然后再问我。谢谢