Blog » PHP » Image upload using php mysqli.

Image upload using php mysqli.

This article will show you how upload images using PHP MYSQL. when the user selects an image , clicks on the submits button, data will store in the database.and image saves in a images root folder.

creating database connection


<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "images";
$con = new mysqli($servername, $username, $password, $database);
if($con->connect_error){
die ('Failed to connect to MySQL: ' . $mysqli->connect_errno);
}
?>


simple image validation


before uploading images, we have to check users added image file type correct or not, therefore we can use this simple script to checking valid image file.


<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(!empty($_FILES['fileimg']['tmp_name'])){
$img = ($_FILES['fileimg']['tmp_name']);
$check = getimagesize($img);
if($check == false) {
die($_FILES['fileimg']['name'] . " is not a valid image file.");
}
}
?>


html form


<form action=""method="post"enctype="multipart/form-data">
<h3>Upload image</h3> 
<input name="fileimg" type="file" id="fileimg" />
<button type="submit" class="upload">Upload</button></form>


complete source code


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>upload-image</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "images";
$con = new mysqli($servername, $username, $password, $database);
if($con->connect_error){
die ('Failed to connect to MySQL: ' . $mysqli->connect_errno);
}
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(!empty($_FILES['fileimg']['tmp_name'])){
$img = ($_FILES['fileimg']['tmp_name']);
$check = getimagesize($img);
if($check == false) {
die($_FILES['fileimg']['name'] . " is not a valid image file.");
}
}
$img= $_FILES['fileimg']['name'];
$temppath= $_FILES['fileimg']['tmp_name'];
move_uploaded_file($temppath,"images/$img");
$stmt = $con->prepare("INSERT INTO upload (img) VALUES (?)"); 
$stmt->bind_param("s", $img);
if($stmt->execute()){
echo "uploaded successfully";
}else{
echo "Failed";
}
}
?>
<form action=""method="post"enctype="multipart/form-data">
<h3>Upload image</h3> 
<input name="fileimg" type="file" id="fileimg" />
<button type="submit" class="upload">Upload</button></form>
</body>
</html>
ARTICLE POSTED BY : Admin

Hi, I'am k.g uththara. I'm a professional web developer. I write blog posts in my free time. if you want to contact me, send a message on contact page, thanks.