How to upload image to database using PHP/MySQL

Here is the simple code to upload files to a particular folder also this will make an entry in database. For example if you are making user registration, this code can be used to store user photo. Use the same user table to store user image.

In this code we have used “file_tbl” table to store user image path. Change the table and database name.

SQL dump:

1
2
3
4
5
6
7
8
9
--
-- Table structure for table `file_tbl`
--
 
CREATE TABLE IF NOT EXISTS `file_tbl` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `path` VARCHAR(200) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

PHP file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image" size="40">
<input name="" type="submit" value="upload" />
 
</form>
<?php 
$con = mysql_connect('localhost', 'root', ''); //Update hostname
mysql_select_db("my_db", $con); //Update database name
 
define ("MAX_SIZE","1000"); 
function getExtension($str)
{
	 $i = strrpos($str,".");
	 if (!$i) { return ""; }
	 $l = strlen($str) - $i;
	 $ext = substr($str,$i+1,$l);
	 return $ext;
}
 
$errors=0;
$image=$_FILES['image']['name'];
if ($image) 
{
	$filename = stripslashes($_FILES['image']['name']);
	$extension = getExtension($filename);
	$extension = strtolower($extension);
	if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") 
		&& ($extension != "gif")&& ($extension != "JPG") && ($extension != "JPEG") 
		&& ($extension != "PNG") && ($extension != "GIF")) 
	{
		echo '<h3>Unknown extension!</h3>';
		$errors=1;
	}
	else
	{
		$size=filesize($_FILES['image']['tmp_name']);
 
		if ($size > MAX_SIZE*1024)
		{
			echo '<h4>You have exceeded the size limit!</h4>';
			$errors=1;
		}
 
		$image_name=time().'.'.$extension;
		$newname="images/".$image_name;
 
		$copied = copy($_FILES['image']['tmp_name'], $newname);
		if (!$copied) 
		{
			echo '<h3>Copy unsuccessfull!</h3>';
			$errors=1;
		}
		else echo '<h3>uploaded successfull!</h3>';
 
		mysql_query("insert into file_tbl (path) values('".$newname."')");
	}
 
	//Display image
	$rs=mysql_query("select * from file_tbl");
	if($rs)
		while($row=mysql_fetch_array($rs))
		{
		 ?>
		 <img width="150" src="<?php echo $row['path'];?>"><br>
		 <?php 
		}
}
?>

Start exploring endless computing possibilities with your own Raspberry Pi computer and accessories. Perfect for beginners and students.

By using the global PHP $_FILES array you can upload files from a client computer to the remote server.

The first parameter is the form’s input name and the second index can be either “name”, “type”, “size”, “tmp_name” or “error”. Like this:

  • $_FILES[“image”][“name”] – the name of the uploaded file
  • $_FILES[“image”][“type”] – the type of the uploaded file
  • $_FILES[“image”][“size”] – the size in bytes of the uploaded file
  • $_FILES[“image”][“tmp_name”] – the name of the temporary copy of the file stored on the server
  • $_FILES[“image”][“error”] – the error code resulting from the file upload

This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.


33 Responses to “How to upload image to database using PHP/MySQL”

  1. this code is working fine
    =======================================================

    <img width="400" height="300" src="”>
    <?php
    }

    //Update database name
    define ("MAX_SIZE","1000");
    function getExtension($str) {

    $i = strrpos($str,".");

    if (!$i) { return ""; }
    $l = strlen($str) – $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
    }
    $errors=0;
    if(isset($_POST['submit'])) {
    $image = $_FILES['image']['name'];
    if ($image)
    {
    $filename = stripslashes($_FILES['image']['name']);
    $extension = getExtension($filename);
    $extension = strtolower($extension);
    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")&& ($extension != "JPG") && ($extension != "JPEG") && ($extension != "PNG") && ($extension != "GIF"))
    {
    echo 'Unknown extension!’;
    $errors=1;
    }
    else
    {
    $size=filesize($_FILES[‘image’][‘tmp_name’]);
    if ($size > MAX_SIZE*1024) {
    echo ‘You have exceeded the size limit!’;
    $errors=1;
    }
    $image_name=time().’.’.$extension;
    $newname=”images/”.$image_name;
    $copied = copy($_FILES[‘image’][‘tmp_name’], $newname);

    if (!$copied) {
    echo ‘Copy unsuccessfull!’;
    $errors=1;
    }
    else echo ‘uploaded successfully!’;

    mysql_query(“insert into image_upload (path) values(‘”.$newname.”‘)”);
    }

    }}else { ?>

    Reply
  2. showing below error
    Warning: copy(images/1441432388.png): failed to open stream: No such file or directory in D:\xammp\htdocs\test_img\index2.php on line 47
    Copy unsuccessful!

    Reply
  3. Labeeb

    Gud evng frndzz….i am new developer……..thnk u fr this smpl code

    Reply
  4. Labeeb

    Guys I would like to create gruop for developers……my no s…8593983010

    Reply

Leave a Reply