0

我有这样的表格:

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

单击提交时,数据存储在数据库中并使用 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;;
        }
      });
    });

在这里,我使用 insert.php 存储数据并使用 another.php 显示,但是当进入图像部分时,我不明白如何将图像存储在 db 中的文件夹和路径中,我的意思是我对在 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";
 }

如果我分开然后图像存储在文件夹中..

如果我分开,那么表单代码是:

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

上传文件.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";
 }
?>

这是完美的工作......

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

4

3 回答 3

1

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

我们将创建一个隐藏的文本区域,它将创建数据字符串,我们将使用 $_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>";
}
?>
于 2013-06-05T12:59:25.787 回答
0

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

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

你必须添加这个

<form method="post" enctype="multipart/form-data" action="insert.php">
于 2014-08-05T16:24:48.677 回答
-1
<?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>";

    }


} ?>

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

于 2013-06-05T11:14:53.300 回答