Rayhan’s blog (raynux.com)

Rayhan’s Personal Web Blog Site

Entries Comments


Store and Display image from MySQL database

20 November, 2008 (16:09) | MySQL, PHP, Reference, programming | No comments

A basic approach to upload and save image to a MySQL database and then display the image from the database.

First you need to create a table in MySQL Database to store the image data. Log into you database and run the following sql command:
CREATE TABLE  `images` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(100) default NULL,
`size` int(11) default NULL,
`type` varchar(20) default NULL,
`content` mediumblob,
PRIMARY KEY  (`id`)
) ENGINE=MyISAM;

Once the table have been created, we are ready to write codes. Now create a folder in you webserver named rayImg and create image.php and upload.php files inside the folder.

Open the image.php, copy and paste the following code and save it.

File: image.php

<?php
	/**
	 * Display image form database
	 *
	 * Retrive an image from mysql database if image id is provided.
	 *
	 * @example to display a image with image id 1, place <img src="image.php?id=1" > in your html file.
	 *
	 * @author Md. Rayhan Chowdhury
	 * @copyright www.raynux.com
	 * @license LGPL
	 */

	// verify request id.
	if (empty($_GET['id']) || !is_numeric($_GET['id'])) {
		echo ‘A valid image file id is required to display the image file.’;
		exit;
	}

	$imageId = $_GET['id'];

	//connect to mysql database
	if ($conn = mysqli_connect(’localhost’, ‘root’, ‘root’, ‘test’)) {
		$content = mysqli_real_escape_string($conn, $content);
		$sql = “SELECT type, content FROM images where id = {$imageId}”;

		if ($rs = mysqli_query($conn, $sql)) {
			$imageData = mysqli_fetch_array($rs, MYSQLI_ASSOC);
			mysqli_free_result($rs);
		} else {
			echo “Error: Could not get data from mysql database. Please try again.”;
		}
		//close mysqli connection
		mysqli_close($conn);

	} else {
		echo “Error: Could not connect to mysql database. Please try again.”;
	}	

	if (!empty($imageData)) {
		// show the image.
		header(”Content-type: {$imageData['type']}”);
		echo $imageData['content'];
	}
?>

Now open the update.php, copy and paste the following code and save it.

File: upload.php

<?php
/**
 * Upload an image to mysql database.
 *
 *
 *
 * @author Md. Rayhan Chowdhury
 * @copyright www.raynux.com
 * @license LGPL
 */

// Check for post data.
if ($_POST && !empty($_FILES)) {
	$formOk = true;

	//Assign Variables
	$path = $_FILES['image']['tmp_name'];
	$name = $_FILES['image']['name'];
	$size = $_FILES['image']['size'];
	$type = $_FILES['image']['type'];

	if ($_FILES['image']['error'] || !is_uploaded_file($path)) {
		$formOk = false;
		echo “Error: Error in uploading file. Please try again.”;
	}

	//check file extension
	if ($formOk && !in_array($type, array(’image/png’, ‘image/x-png’, ‘image/jpeg’, ‘image/pjpeg’, ‘image/gif’))) {
		$formOk = false;
		echo “Error: Unsupported file extension. Supported extensions are JPG / PNG.”;
	}
	// check for file size.
	if ($formOk && filesize($path) > 500000) {
		$formOk = false;
		echo “Error: File size must be less than 500 KB.”;
	}

	if ($formOk) {
		// read file contents
		$content = file_get_contents($path);

		//connect to mysql database
		if ($conn = mysqli_connect(’localhost’, ‘root’, ‘root’, ‘test’)) {
			$content = mysqli_real_escape_string($conn, $content);
			$sql = “insert into images (name, size, type, content) values (’{$name}’, ‘{$size}’, ‘{$type}’, ‘{$content}’)”;

			if (mysqli_query($conn, $sql)) {
				$uploadOk = true;
				$imageId = mysqli_insert_id($conn);
			} else {
				echo “Error: Could not save the data to mysql database. Please try again.”;
			}

			mysqli_close($conn);
		} else {
			echo “Error: Could not connect to mysql database. Please try again.”;
		}
	}
}
?>

<html>
	<head>
		<title>Upload image to mysql database.</title>
		<style type=”text/css”>
			img{
				margin: .2em;
				border: 1px solid #555;
				padding: .2em;
				vertical-align: top;
			}
		</style>
	</head>
	<body>
		<?php if (!empty($uploadOk)): ?>
			<div>
		  		<h3>Image Uploaded:</h3>
		  	</div>
			<div>
				<img src=”image.php?id=<?=$imageId ?>” width=”150px”>
				<strong>Embed</strong>: <input size=”25″ value=’<img src=”image.php?id=<?=$imageId ?>”>’>
			</div>

			<hr>
		<? endif; ?>

		<form action=”<?=$_SERVER['PHP_SELF']?>” method=”post” enctype=”multipart/form-data” >
		  <div>
		  	<h3>Image Upload:</h3>
		  </div>
		  <div>
		  	<label>Image</label>
		  	<input type=”hidden” name=”MAX_FILE_SIZE” value=”500000″>
			<input type=”file” name=”image” />
		    <input name=”submit” type=”submit” value=”Upload”>
		  </div>
		</form>
	</body>
</html>

Replace line

mysqli_connect(’localhost’, ‘root’, ‘root’, ‘test’)

with

mysqli_connect(’your host’, ‘your username’, ‘your password’, ‘your database name’)

in both the file and save again.

You are done. Open upload.php from your browser and upload you desired image and view the uploaded image.

Last evening at Fantasy Kingdom

16 November, 2008 (08:07) | Travel, personal | No comments

Jubel, my best friend at Sylhet came to Dhaka for a 2 days trip. To give him some excitements we went to Fantasy Kingdom last day. We reached there at about 5 PM. We rode on some exciting rides like roller coaster, flying bird etc. It was an exciting and enjoyable evening for both of us.

Here are some photos of the tour taken by my Motorola V3i mobile phone.

15-11-08_1919

15-11-08_1918

15-11-08_1914

15-11-08_1921

View all pictures: http://www.flickr.com/photos/raynux/tags/fk15nov/

Recovering Ubuntu or Fedora Linux after installing windows

21 September, 2008 (01:40) | Fedora, Linux, Reference, Ubuntu | 2 comments

Running linux with windows in dual boot mode is not hassle free at all. Specially if you reinstall or repair windows, your linux system will disappear. As a newbie you may stop using linux or reinstall it again instead of solving the problem. In this article I will share my experience on how to recover the boot option for linux. I will cover two well known linux distro ubuntu 8 and fedora 7. I will try to cover the fail safe situation here.

In both Fedora and Ubuntu this task includes two basic steps. These are:

  • Enter into your existing hard disk linux system.
  • Setup GRUB Boot Loader using GRUB program.

a. Enter into your existing hard disk linux system.

Fedora 7:

In fedora recovering grub is easy task as fedora automatically mount the existing system image to /mnt/sysimage in rescue mode.

  1. Insert the fedora installation cd to boot from cd.
  2. When the boot menu appear enter the rescue mode. A message will be prompt saying mounting the existing fedora system on /mnt/sysimage, click ok.
  3. In rescue mode you will be in a shell
  4. Enter the following command
    #chroot /mnt/sysimage
  5. Now you are in your existing fedora operating system.

Ubuntu 8.04 LTS:

In ubuntu you will have to mount the existing system image manually.

  1. Insert the ubuntu live cd and start a live session from cd.
  2. open the terminal window
  3. the following command will display currently mounted device or harddisk partitions
    #df -h
  4. get the device name for /boot if exists or / (root) partition say /dev/sda9.
  5. enter the following command
    #sudo mkdir ubuntu
    #sudo mount -t ext3 /dev/sda9 ubuntu
  6. If you have separate /usr partition say /dev/sda7 enter the following command too.
    #sudo mount -t ext3 /dev/sda7 ubuntu/usr
  7. Enter the following command to mount /proc and /dev and change chroot.
    #sudo mount -t proc none ubuntu/proc
    #sudo mount -o bind /dev/ ubuntu/dev
    #sudo chroot ubuntu /bin/bash
  8. Now you are in your existing ubuntu operating system.

b. Setup GRUB Boot Loader using GRUB program.

In grub you are mainly required to find the boot device and set the root to bood device.

  1. Insert the ubuntu live cd and start a live session from cd.
    #grub
  2. Find the existing boot device using following command. Which will out put something like (hd0,0) or (hd0,5) say (hdX,Y).
    #grub> find /boot/grub/stage1
  3. Use the above output in the following two commands.
    #grub> root (hdX,Y)
    #grub> setup (hdX)
    #grub> quit
  4. if everything is ok then you are done. just reboot the system.

This article is completely based on my current experience and I am still a newbie in linux environment. so there may have sevaral other options to do the same task.

Panam City Tour- Esha Khan’s Sonargoan, Old capital

22 August, 2008 (01:14) | Bangladesh, personal | No comments

Sonargoan . Panam City

It was Sunday, August 17, 2008. I got up at 10:00 O’clock because it was a government holiday. Probir came to my room saying about going some where. I was not prepare for this, in a sudden I told him to go Sonargoan of Esha Khan. Then I and probir convinced Zaed to accompany us which took about 1 hour.

Finally we started our journey toward Sonargoan at 11:30 AM from. Because of holiday we managed to reach there at about 1 pm. It was an imaging journey as none of we ever visited the place. We were in the dream when we entered the narrow street of Panam city. All the building standing two sides of the road were about 3 hundred years old. Most of them were in danger and any time could collapse. We learned the architecture of the then era. The structure of the building was our main subject as all of we were civil engineer. All the buildings were made using lime-concrete technology. In some building steel joist was used to bear the load of slab but most of the buildings were made of lime-concrete only even in the tension zone like slab. In the tension zone they used brick blocks in 45 degree angle so that they can act as compression member to resist tension like arch do. We found visible cracks here and there in most of the buildings. It was really a good experience for us.

But what we found was all the buildings were decaying and emergency look after and quality renovation work is highly required. The government is doing for some renovation work which is not sufficient. We need to save it because it is our Heritage. Finally we returned home with a great memory.

Tour Pictures

All the pictures were taken by mobile phone.

1
(I, Probir and our two little guide ridoy and autip.)

11
(I was thinking ….?)

10
(Picture of a dangerous slabs see bricks are in 45 degree angle.)

13
(Close view of a decaying wall made of lime concrete)

16
(Zaed, what is he doing with his guava)

View Photo Album of Panam Tour >

Listen MP3 on Fedora Linux box.

20 July, 2008 (00:03) | Fedora, Linux, Reference | 1 comment

I receives lots of call from my friends to help them fixing mp3 problem in fedora. Some of them already have internet connection to their fedora box.

Here is a single command what can solve the problem if you have internet connection.


# yum -y install gstreamer*

This command will automatically find, download and install the GStreamer mp3 codec for you. Then you can enjoy the mp3 song with your favorite music player.

You can download xmms one of the popular mp3 player on your fedora system. It is a Winamp alternative to linux. To install this software enter the following command.


# yum -y install xmms*

After installing xmms you will find the menu Application -> Sound & Video -> Audio Player to launch the xmms player.

Varification Post for Technorati.com

19 July, 2008 (23:32) | Uncategorized | 1 comment

GPRS Connection from fedora linux using my moto L6

19 July, 2008 (22:19) | Fedora, Linux, Reference | 2 comments

This is how I connect to internet from fedora box using my motorola L6 GPRS modem. I use this procedure with Teletalk connection.

After a fresh fedora installation I enter the following command in the shell. This command creates a wvdial configuration file for my modem.

# wvdialconf /etc/wvdial.conf

Now I need to modify some contents of wvdial.conf file. To do so I open the /etc/wvdial.conf using VI or other text editor. And replace the content of the file with the following text and save it.


[Dialer Defaults]
Modem = /dev/ttyACM0
Baud = 460800
Init1 = ATZ
Init2 = ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0
ISDN = 0
Modem Type = USB Modem
Phone = *99#
Username = A
Password = B
Stupid Mode = 1

I make sure to set username = A, Password=B and Stupid Mode = 1 and do not modify the line

Modem = .....

as this is my device name (this line can very with your phone set). Now whenever I need to connect to internet I just enter the following command to the shell.

# wvdial

Thats all. Same way you can turn your mobile set to internet from fedora with no or little modification.

I have started learning both Ruby & Python

15 July, 2008 (23:58) | Python, Ruby, programming | No comments

Today I have started learning Python, after a successful start I have found that in Python the code block is separated by indent. That means no closing braces or ending identifier. like


def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append(”property of the zoo”)
    return penguin
  
def another_func():
    return 1

Here, the function definition ends at after a blank line followed by another definition. I was disappointed with this features of Python and found it is confusing for a large code base for manageability.

As a result I moved to Ruby. After installing Ruby in my PC I started learning the basics of Ruby Language. I have found some interesting features in Ruby language. But I am not impressed with some features like the way of return statement in a function definition.

This is my opinion as a beginner. Yet, I want to try both of them.

I have updated my resume.

10 July, 2008 (11:20) | personal | No comments

Last night I have renewed my resume. It took me about 4 hour to make it good. Here is the link to my resume.

Good commenting practice in PHP.

26 June, 2008 (12:50) | CakePHP, PHP, Reference, programming | No comments

Currently I am working on the documentation of my software written in PHP. From this documentation project I have found that proper commenting of code is a good documentation. If you write your code base along with comment then you don’t need to worry about the API Documentation of your software. You just have to use some software like PHPDoc or Doxygen to make the API in a minute. Specially I am using Doxygen in my project which is also used in CakePHP API documentaiton.

When you are commenting your code be careful to meet the commenting requirement/procedure so that those documentation software can understand your comment as a data.

Here is a simple example what Doxygen can easily parse for you.

    
/**
 * Class A.
 *
 * Class description.
 *
 * @example example here.
 * @todo to do here
 *
 * @package appname
 * @subpackage appname.subname
 * @author yourname
 * @since version 1.0
 */
class A extends Object{
	/**
	 * Enter description here...
	 *
	 * @var type
	 */
	var $member1;
	/**
	 * Enter description here...
	 *
	 * @param integer $param1
	 * @param string $param2
	 * @param array $param3 contains a array of data
	 * @return boolean
	 * @since version 2.0
	 */
	function doSomeThing($param1, $param2, $param3){
		return true;
	}
}
    

So if you follow the commenting technique carefully, you don’t have to white API of your own.

« Older entries

 

Free cPanel hosting provided by GOOD HOST