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

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。