Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Storing Images in MySQL with PHP

mysql

  • Please log in to reply
4 replies to this topic

#1 Tongleang

Tongleang

    CC Lurker

  • New Member
  • Pip
  • 4 posts
  • Programming Language:C
  • Learning:C

Posted 11 October 2012 - 12:09 AM

Hi.
I want to show image on browser. I have code below:
*** Create database and table**
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE tbl_image
(
	id tinyint(3) unsigned NOT NULL auto_increment,
	image blob NOT NULL,
	PRIMARY KEY (id)
)";
// Execute query
mysql_query($sql,$con);

mysql_close($con);
?>
***File insert.php**
<?php
// Create MySQL login values and
// set them to your login information.
$username = "root";
$password = "";
$host = "localhost";
$database = "my_db";

// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!$link) {
		die('Could not connect: ' . mysql_error());
}

// Select your database
mysql_select_db ($database);

// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {

		 // Temporary file name stored on the server
		 $tmpName = $_FILES['image']['tmp_name'];
		
		 // Read the file
		 $fp	 = fopen($tmpName, 'r');
		 $data = fread($fp, filesize($tmpName));
		 $data = addslashes($data);
		 fclose($fp);
		

		 // Create the query and insert
		 // into our database.
		 $query = "INSERT INTO tbl_image ";
		 $query .= "(image) VALUES ('$data')";
		 $results = mysql_query($query, $link);
		
		 // Print results
		 print "Thank you, your file has been uploaded.";
		
}
else {
print "No image selected/uploaded";
}

// Close our MySQL Link
mysql_close($link);
?>

*****file add.html**
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[url="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd%22>"]http://www.w3.org/TR...nsitional.dtd">[/url]
<html xmlns="[url="http://www.w3.org/1999/xhtml%22>"]http://www.w3.org/1999/xhtml">[/url]
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
	<form enctype="multipart/form-data" action="insert.php" method="post" name="changer">
	<input name="MAX_FILE_SIZE" value="102400" type="hidden">
	<input name="image" accept="image/jpeg" type="file">
	<input value="Submit" type="submit">
</body>
</html>

*****file showimage.php****
<?php

$username = "root";
$password = "";
$host = "localhost";
$database = "my_db";

mysql_connect($host, $username, $password) or die("Can not connect to database: ".mysql_error());

mysql_select_db($database) or die("Can not select the database: ".mysql_error());

$id = $_GET['id'];

if(!isset($id) || empty($id) || !is_int($id)){
		 die("Please select your image!");
}else{

$query = mysql_query("SELECT * FROM tbl_image WHERE id='".$id."'");
$row = mysql_fetch_array($query);
$content = $row['image'];

header('Content-type: image/jpeg');
		 echo $content;
}
?>
When I run it. It's show error message as below.
Notice:Undefined index: id in D:\PHP\PHP Learn By Myselt\showimage.php on line 12

How to reslove this problem. Please help me.

Edited by Tongleang, 11 October 2012 - 04:32 PM.
Added code tags

  • 0

#2 BlackRabbit

BlackRabbit

    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts
  • Location:Argentina
  • Programming Language:C, C++, C#, PHP, JavaScript, Transact-SQL, Bash, Others
  • Learning:Java, Others

Posted 11 October 2012 - 02:59 AM

could you please paste here the precise error message you get ?
se we can start the problem analysis from there
  • 0

#3 VNFox

VNFox

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 648 posts
  • Programming Language:C#, PHP
  • Learning:Assembly

Posted 11 October 2012 - 08:35 AM

The topic indicates PHP ... but it's in Perl section ... aiyyyyyyyyy ... yup .. what's the error message?
  • 0

www.pickmike.com
I don't just develop software. I find solutions to your business needs.


#4 BenW

BenW

    CC Devotee

  • Community Manager
  • 976 posts
  • Programming Language:ActionScript
  • Learning:ActionScript

Posted 11 October 2012 - 09:12 AM

I've moved this topic to the PHP section as that seems to be where it should be. If it was actually a Perl problem, then the issue is that you're using PHP code :laugh:

Please remember to use the code tags in your posts - I've added them for you this time, though :)
  • 0

fss_overall.png

 


#5 Tongleang

Tongleang

    CC Lurker

  • New Member
  • Pip
  • 4 posts
  • Programming Language:C
  • Learning:C

Posted 18 October 2012 - 04:20 PM

Hi! I have 5 file like below:

*****create database and table****
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
// Create database
if (mysql_query("CREATE DATABASE my_dbimg",$con))
  {
  echo "Database created";
  }
else
  {
  echo "Error creating database: " . mysql_error();
  }
// Create table
mysql_select_db("my_dbimg", $con);
$sql = "CREATE TABLE img_tbl
(
id int(4) NOT NULL AUTO_INCREMENT,
img_name varchar(255) collate latin1_general_ci NOT NULL,
img_type varchar(4) collate latin1_general_ci NOT NULL,
img_size int(8) NOT NULL,
img_data blob NOT NULL,
PRIMARY KEY (id)
)ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>

***create form upload***
FORM NAME="f1" METHOD="POST" ACTION="upload.php" ENCTYPE="multipart/form-data">
<table>
<tr><td> Image Upload Page </td></tr>
<tr><td> <input type="file" name="imgfile"/></td></tr>
<tr><td> <input type="submit" name="submit" value="Save"/> </td></tr>
</table>
</FORM>
****file dbconfig.php***
<?
  $dbhost    = "localhost"; // server host name
  $dbusr =   "root"; // mysql username to connect
  $dbpass    = ""; //password
  $dbname    = "my_dbimg"; //database name to select to
?>
****file upload.php***
<?
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname, $dbconn);
if(isset($_REQUEST['submit']) && $_FILES['imgfile']['size'] > 0)
{
  $fileName=$_FILES['imgfile']['name']; // image file name
  $tmpName=$_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
  $fileSize=$_FILES['imgfile']['size']; // size of the uploaded file
  $fileType=$_FILES['imgfile']['type']; // file type
// Read the file
  $fp = fopen($tmpName, 'r');
  $imgContent = fread($fp, filesize($tmpName));
  $imgContent = addslashes($data);
  $imgContent1=base64_encode($imgContent);
  fclose($fp); // close the file handle
 
  $query = "INSERT INTO img_tbl ('img_name','img_type','img_size','img_data') VALUES ('$fileName','$fileType', '$fileSize','$imgContent1')";
 
  mysql_query($query) or die('Error, query failed');
  $imgid = mysql_insert_id(); // autoincrement id of the uploaded entry
  mysql_close($dbconn);
 
   echo "<br>Image successfully uploaded to database<br>";
  echo "<a href=\"viewimage.php?id=$imgid\">View Image</a>";
 
}else die("You have not selected any image");
?>
*****file viewimage.php***
<?
if(isset($_REQUEST['id']))
{
   // get the file with the id from database
  include "dbconfig.php";
  $dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
  mysql_select_db($dbname, $dbconn) or die("Unable to select database");
  $id= $_REQUEST ['id'];
  $query = "SELECT 'img_name','img_type','img_size','img_data' FROM img_tbl WHERE id = '$id'";
  $result = mysql_query($query) or die(mysql_error());
  list($name, $type, $size, $content) = mysql_fetch_array($result);
  header("Content-length: $size");
  header("Content-type: $type");
  print base64_decode($content);
  mysql_close($dbconn);
}
?>

***file showimages.php****
<?
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
$query = "SELECT 'id','img_name','img_type','img_size','img_data' FROM img_tbl ORDER BY 'id'";
$result = mysql_query($query) or die('Error, query failed');
while($row = mysql_fetch_array($result)){
echo "<img src=\"viewimage.php?id=$row[id]\" width=\"55\" height=\"55\"/> <br/>";
}
mysql_close($dbconn);
?>

When I run tbluploadimg.html it show message like below:

0) { $fileName=$_FILES['imgfile']['name']; // image file name $tmpName=$_FILES['imgfile']['tmp_name']; // name of the temporary stored file name $fileSize=$_FILES['imgfile']['size']; // size of the uploaded file $fileType=$_FILES['imgfile']['type']; // file type // Read the file $fp = fopen($tmpName, 'r'); $imgContent = fread($fp, filesize($tmpName)); $imgContent = addslashes($data); $imgContent1=base64_encode($imgContent); fclose($fp); // close the file handle $query = "INSERT INTO img_tbl ('img_name','img_type','img_size','img_data') VALUES ('$fileName','$fileType', '$fileSize','$imgContent1')"; mysql_query($query) or die('Error, query failed'); $imgid = mysql_insert_id(); // autoincrement id of the uploaded entry mysql_close($dbconn); echo "
Image successfully uploaded to database
"; echo "View Image"; }else die("You have not selected any image"); ?>

How to resolve it. Help me.
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download