How to Upload File in Database using PHP 8?

Jun 01, 2022 . Admin



Hello Friends,

This article will provide example of How to Upload File in Database using PHP 8?. I would like to show you Upload and Store File in Database using PHP 8 and MySQL. you will learn How to insert File in MySQL database using PHP 8?. it's simple example of How To Upload And Insert File Into Mysql Database Using Php And Html. Follow bellow tutorial step of Upload File in PHP MySQL Database Example.

I will give you simple example of How to upload Files into MySQL database using PHP 8.

So, let's see bellow solution:

index.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to Upload File in Database using PHP 8?</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<?php 
if (isset($_FILES['file'])) {
    
$file_name = $_FILES['file']['name'];    
$file_size = $_FILES['file']['size'];    
$file_tmp = $_FILES['file']['tmp_name'];     
$file_type = $_FILES['file']['type'];        

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_php";

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("connection failed:" .mysqli_connect_error());
    echo "connection successfull";
}

    $sql="INSERT INTO files(file,type,size) VALUES('$file_name','$file_type','$file_size')";
    
    if ($conn->query($sql)===TRUE) {
        echo " ";
    }else{
        $msg = "<h5 class='alert alert-primary'>Error :".$sql."<br>".$conn->error."</h5>";
    }
    
    if (move_uploaded_file($file_tmp ,"pathname/".$file_name)) {
        $msg = "<h5 class='alert alert-primary'>File inserted Successfully!</h5>";
    }else{
        $msg = "<h5 class='alert alert-primary'>File Was Not inserted!</h5>";
    }
}
?>
    <div class="container mt-5">
        <div class="card">
            
            <div class="card-header text-center bg-primary text-white">
                <h3>How to Upload File in Database using PHP 8? -Mywebtuts.com</h3>
            </div>
            
            <div class="card-body" style="height: 200px;">
                <?php echo $msg; ?>
                <form action="" method="post" enctype="multipart/form-data" > 
                    <input type="file" name="file" class="form-control" class="custom-input-file">
            </div>
            
            <div class="d-flex justify-content-center pb-5">
                    <input type="submit" name="upload" class="btn btn-primary"></input>
                </form>
            </div>
        
        </div>
    </div>
</body>
</html>

Output:

It will help you...
#PHP 8