<?php
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','myfile');
// Establish database connection.
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e)
{
exit("Error: " . $e->getMessage());
}
?>
index.php
<php
session_start();
error_reporting(0);
include "config.php";
// Uploads files
if(isset($_POST['save'])) { // if save button on the form is clicked
$filename=$_FILES["filename"]["name"];
move_uploaded_file($_FILES["filename"]["tmp_name"],"media/".$_FILES["filename"]["name"]);
$sql = "INSERT INTO fileupload (filename) VALUES ('$filename')";
if (mysqli_query($conn, $sql))
{
echo "<script>alert('Uploaded successfully');</script>";
}
else {
echo "<script>alert('Failed to upload');</script>";
}
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>How to save images in Mysql database</title>
<!--Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css" type="text/css">
</head>
<body>
<p><br></p>
<div class="container">
<h3>Upload pdf/docs/zipped files</h3>
<form class="form-horizontal row-fluid" name="insertproduct" method="post" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="basicinput">Upload file</label>
<div> </div>
<div class="controls">
<input type="file" name="imagename" id="filename" value="" class="span8 tip" required>
</div>
</div>
<div class="form-group row pt-3">
<div class="col-12">
<button type="submit" class="btn btn-success" name="save">
<i class="fa fa-plus "></i> Upload
</button>
</div>
</div>
</formv
<table id="" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>File Name</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * from fileupload order by ID desc";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{
?>
<tr>
<td><?php echo $cnt;?></td>
<td><img class="" src="media/<?php echo $result->filename;?>" alt="Image" width="100" height="80"></td>
<td><?php echo ($result->filename) ?></td>
</tr>
<?php
$cnt=$cnt+1;
}
} ?>
</tbody>
</table>
</div>
</body>
</html>
Download