2016-12-12 54 views
1

我有一個網頁用戶可以上傳文件。現在,代碼可以成功將文檔上傳到服務器上的目錄,而不會出現任何問題。但是,我需要將文檔作爲新插入的行上載到MySQL表中,然後將文檔顯示爲原始網頁上的鏈接。然而,每次我嘗試上傳到MySQL時,它都會失敗,我不確定這是爲什麼。我在調試模式下收到0錯誤,我可以登錄併成功連接到數據庫。我的查詢是失敗的,但我可以在MySQL中成功運行查詢而不會出錯。使用PHP將文件上傳到MySQL數據庫

我的代碼:

HTML:

<body> 

<br/> 

<div id="bodydiv"> 

<fieldset id='title'> 

    <span style='color:aliceblue'>Uploaded SG Documents</span> 

</fieldset> 

<br/> 


<fieldset id='docTypeWO'> 

    <span>Scanned Work Orders:</span> 

    <div id='responseWO'> 

    </div> 

</fieldset> 


<br/> 


<fieldset id='docTypeCS'> 

    <span>Cut Sheets:</span> 

    <div id='responseCS'> 

    </div> 

</fieldset> 


<br/> 


<fieldset id='docTypeOther'> 

    <span>Others:</span> 

    <div id='responseOther'> 

    </div> 

</fieldset> 


<br/> 


<form name="sgFileUpload" id="sgFileUpload" action='sg_addupload.php' method="POST" enctype="multipart/form-data"> 




<fieldset id='uploadBtnField'> 

    <input type="hidden" name="MAX_FILE_SIZE" value="50000000"/> 


    <input type='file' name='searchFile' id='searchFile' multiple> 

    <input type='submit' name='startUpload' id='startUpload' value='Upload'> 

    <!-- <input type='reset' name='cancelUpload' id='cancelUpload' value="Cancel Upload"> 

    <input type='button' name='deleteFile' id='deleteFile' value='Delete'> --> 

</fieldset> 

<!-- The table listing the files available for upload/download --> 
    <table><tbody></tbody></table> 



    </form> <!-- End Form Input --> 

</div> 

</body> 
</html> 

我的AJAX:

   j('#startUpload').on('click', function() { 
        var file_data = j('#searchFile').prop('files')[0]; 
        var form_data = new FormData();     
        form_data.append('file', file_data); 
        alert(form_data);        
        j.ajax({ 
          url: 'sg_addupload.php', // point to server-side PHP script 
          dataType: 'text', // what to expect back from the PHP script, if anything 
          cache: false, 
          contentType: false, 
          processData: false, 
          data: form_data,       
          type: 'POST', 
          success: function(data){ 
           j('#responseWO').html(data); // display response from the PHP script, if any 
          } 
        }); 
       }); 

我的PHP:

include('inc.php'); 


//This section works successfully to upload to a directory on the server. 

if (0 < $_FILES['file']['error']) { 
    echo 'Error: ' . $_FILES['file']['error'] . '<br>'; 
} 
else { 
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']); 
} 





//This section fails... 


    //This is the directory where images will be saved 
    $target = "uploads/"; 
    $target = $target . basename($_FILES['file']['name']); 


    //This gets all the other information from the form 
    $fileName = basename($_FILES['file']['name']); 
    $tmpName = $_FILES['file']['tmp_name']; 
    $fileSize = $_FILES['file']['size']; 
    $fileType = $_FILES['file']['type']; 

    $fp  = fopen($tmpName, 'r'); 
    $content = fread($fp, filesize($tmpName)); 
    $content = addslashes($content); 
    fclose($fp); 


    if(!get_magic_quotes_gpc()) 
    { 
     $fileName = addslashes($fileName); 
    } 



    //Writes the Filename to the server 
    if(move_uploaded_file($_FILES['file']['tmp_name'], $target)) { 

     //Tells you if its all ok 
     echo "The file ". basename($_FILES['file']['name']). " has been uploaded, and your information has been added to the directory"; 


     //connect to the database 
     $conn = new mysqli($servername, $username, $password, $dbname); 

     // Check connection 
     if(mysqli_connect_errno()) { 
      printf('Could not connect: ' . mysqli_connect_error()); 
      exit(); 
      } 

     $conn->select_db($dbname); 

     if(! $conn->select_db($dbname)) { 
      echo 'Could not select database. '.'<BR>'; 
     } 


     //Writes the information to the database 
     mysqli_query("INSERT INTO sg_uploads(sgref,file,type,size,content,doctype) VALUES('4','$fileName','$fileType','$fileSize','$content','Other')"); 
     } else { 
      //Gives an error if its not 
      echo "Sorry, there was a problem uploading your file."; 
     } 

所有幫助表示讚賞。謝謝!

+1

** WARNING **:當使用'mysqli'你應該使用參數化查詢,而['bind_param'](http://php.net/manual/en/ mysqli-stmt.bind-param.php)將用戶數據添加到您的查詢中。 **不要**使用字符串插值或連接來完成此操作,因爲您將創建嚴重的[SQL注入漏洞](http://bobby-tables.com/)。 **絕不**將'$ _POST'數據直接放入查詢中。 – tadman

+0

我還是新來綁定參數...我怎麼能做到這一點做一個MySQL插入語句? – rdimouro

+0

你是什麼意思「新來」?這是一種方法。你叫它。該文檔有幾十個例子,更多的意見。用'?'替換查詢中的所有'$ ...'類型值,然後使用適當類型的'bind_param'。需要花費十分鐘的時間才能找出問題,並且可以節省數小時和數小時的調試時間,甚至可以讓您的職業生涯保持穩定。 – tadman

回答

2
<?php 
error_reporting(E_ALL^E_DEPRECATED); 
if(isset($_POST['btn-upload'])) { 
include '../includes/dbcon.php'; 

    $file = $_FILES['file']['name']; 
    $file_loc = $_FILES['file']['tmp_name']; 
    $file_size = $_FILES['file']['size']; 
    $file_type = $_FILES['file']['type']; 
    $title = mysqli_real_escape_string($con, $_POST['title']); 
    $keywords = mysqli_real_escape_string($con, $_POST['keywords']); 
    $categ = mysqli_real_escape_string($con, $_POST['categ']); 
    $email = mysqli_real_escape_string($con, $_POST['email']); 
    $art_info = mysqli_real_escape_string($con, $_POST['art_info']); 
    $folder="../uploads_art_jou/"; 

$allowed = array('pdf','doc' ,'docx'); 
    $file = $_FILES['file']['name']; 
    $ext = pathinfo($file, PATHINFO_EXTENSION); 
$file = $folder."$file";  
    //$location =mysqli_real_escape_string ($con, $_POST['location']); 

    // new file size in KB 
    $new_size = $file_size/1024; 
    // new file size in KB 

    // make file name in lower case 
    $new_file_name = strtolower($file); 

//checks file extension for images only 

     if(!in_array($ext,$allowed)) 
      { 
?> 
<script> 
     alert('file extension not allowed'); 
     window.location.href='art_jou_add.php?file_type_not_allowed_error'; 
</script> 

<?php 
    } 

//check whether file exist in said folder 

     elseif (file_exists($file)) 
      { 
?> 
<script> 
     alert('file already exist'); 
     window.location.href='art_jou_add.php?file_exist'; 
</script> 
<?php 
    } 

//if file does not exist, move it to folder and save details to table 
    else(move_uploaded_file($file_loc,$folder.$file)); 
    { 

    $sql="INSERT INTO art_jou(file,type,size,title,keywords,categ,email,art_info) 
      VALUES('$file','$file_type','$file_size','$title','$keywords','$categ','$email','$art_info')"; 
    mysqli_query($con,$sql); 
    echo "it is done"; 
?> 

<?php 
    } 

    } 

?> 

這對我的作品

+0

上的成員函數請給該代碼添加一點解釋,爲什麼它的工作,你做了什麼不同? – luk2302

+0

我創建了一個數據庫字段(文件,類型,大小,標題,關鍵字,類別,電子郵件,art_info),然後我創建了一個文件夾上傳。這非常有效。該代碼已正確註釋以提供指導 –

相關問題