MySql:如何在数据库中存储文件?

时间:2017-01-12 10:34:45

标签: php mysql mysqli

似乎无法将数据库上传到数据库中。

这是我的代码

这是连接数据库的文件connectiontwo.php

<?php
 $servername = "localhost";
 $username = "root";
 $password = "";
 $dbname = "uphslletreviewer";

 // Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
 // Check connection
 if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
 }

 ?>

这是代码,以便可以上传到数据库

<?php
 include_once 'connectiontwo.php';
 if(isset($_POST['btn-upload']))
 {    

 $file = rand(1000,100000)."-".$_FILES['file']['name'];
 $file_loc = $_FILES['file']['tmp_name'];
 $file_size = $_FILES['file']['size'];
 $file_type = $_FILES['file']['type'];
 $folder="uploads/";

 // 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);
 // make file name in lower case

 $final_file=str_replace(' ','-',$new_file_name);

 if(move_uploaded_file($file_loc,$folder.$final_file))
 {
 $sql="INSERT INTO module_let(module_desc,type,size)       VALUES('$final_file','$file_type','$new_size')";
 $conn->query($sql);
 ?>
 <script>
  alert('successfully uploaded');
    window.location.href='indexsample.php?success';
    </script>
<?php
 }
else
 {
?>
<script>
alert('error while uploading file');
    window.location.href='indexsample.php?fail';
    </script>
<?php
}
}
?>

你的帮助将不胜感激...我是php的新手,所以我来到这里寻求你的帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

您应该检查查询是否成功,如果没有,请在某处记录/打印错误。

if($conn->query($sql) === TRUE) {
     // successful
} else {
     // Errorhandling
     // for finding the error a simple
     echo $conn->errno.": ".$conn->error
}

正如萨米已经提到的那样,你应该使用准备好的陈述: http://php.net/manual/en/mysqli.prepare.php