How to fetch files from database in PHP using MySQL database | E-codec

How to fetch files from database in PHP using MySQL database

 

 

<?php 
// constant define
define('SITE_ROOT_URL', 'http://localhost/youtube/upload-document/');

// Database connection
$conn = mysqli_connect("localhost", "root", "", "youtube");
if(!$conn){
    echo "Database not connected";
    die();
}

if(isset($_POST['submit'])){

    $file = $_FILES['upload'];

    $file_name = $file['name'];
    $tmp_name = $file['tmp_name'];

    $path = $_SERVER['DOCUMENT_ROOT'].'/youtube/upload-document/upload/';

    if(move_uploaded_file($tmp_name, $path.$file_name)){
        $res = mysqli_query($conn, "INSERT INTO photos(document) VALUES('$file_name')");
        if($res){
            echo "Document save and upload successfully.";
        }else{
            echo "Document upload but not data save.";
        }
    }else{
        echo "Document failed to upload";
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="<?=$_SERVER['PHP_SELF']?>" method="POST" enctype="multipart/form-data">
        <input type="file" name="upload" required>
        <input type="submit" name="submit">
    </form>
    <table border="1">
        <thead>
            <tr>
                <th>Sl No.</th>
                <th>Photo</th>
            </tr>
        </thead>
        <tbody>
            <?php 
                $i = 1;
                $res = mysqli_query($conn, "SELECT * FROM photos");
                while($rows = mysqli_fetch_assoc($res)){ ?>
                <tr>
                    <td><?=$i++?></td>
                    <td><img src="<?=SITE_ROOT_URL?>upload/<?=$rows['document']?>" alt="<?=$rows['document']?>" width="100px"></td>
                </tr>
            <?php } ?>
        </tbody>
    </table>
</body>
</html>

PHP File Upload | How to upload a file in PHP

I hope you enjoyed this video tutorial. If you had any doubts, then please comment them below. And if you enjoyed this tutorial, then please hit the like button below and subscribe my channel. Thank you.

Post a Comment

0 Comments