繁体   English   中英

如何在PHP中上传文件并将信息存储在SQLi数据库中?

[英]How to upload file in PHP and store information in SQLi database?

因此,我正在尝试执行此文件上传,并将信息(例如文件大小,名称和URL)存储在数据库中,同时使文件仅上传到计算机上的文件夹中(出于测试目的)。 它没有问题,我唯一遇到的问题是我想要的信息没有存储在数据库中。

if($_SERVER['REQUEST_METHOD']=='POST') {
$target_dir = "uploads/";
$file_name=basename($_FILES["fileToUpload"]["name"]);
$target_file = $target_dir . $file_name;
$fileSize=$_FILES["fileToUpload"]["size"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$complete=$file_name.$imageFileType;
$myUrl=$target_dir.$complete;

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
 // Check file size
if ($_FILES["fileToUpload"]["size"] > 10000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
 }
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "pdf" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only PDF, JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $mysqli=connect();
        $stmt=$mysqli->prepare('INSERT INTO tbl_file (file_name,file_title,file_size,file_url) VALUES (?,?,?,?)') or die(mysqli_error());

        $stmt->execute();
        $stmt->bind_param('ssis',$complete,$file_name,$fileSize,$myUrl);
        $stmt->close();
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.<br>";

    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}}

它必须与SQL语句有关,但是我看不出它是什么,有什么想法吗?

我看到您在调用execute()之后调用了bindParameters()方法。 反之亦然。

$stmt->bind_param('ssis',$complete,$file_name,$fileSize,$myUrl);
$stmt->execute();

...

我认为这可能是您使用错误方法打开与MySQL服务器的新连接的原因。

您可以创建一个新的连接,如下所示:

$mysqli=new mysqli("dbhost","username","passwd","dbname"); 

要么

$mysqli=new mysqli();
$mysqli->connect("dbhost","username","passwd","dbname");

要么

$connection = mysqli_connect("dbhost","username","passwd","dbname");

另外,必须首先绑定参数,然后执行sql。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM