Please follow me on www.ruzdi.com


I just move to my to the my own domain please follow me on www.ruzdi.com

Simple way to install ns2 in ubuntu 10.10


Following is the 10 easy steps of installing ns2 on Ubuntu-10.10

Step1 : Download ns-allinone-2.34 package .

Step2 : Place the ns-allinone-2.34.tar.gz file in under your home folder and extract it using following command

tar xvfz ./ns-allinone-2.34.tar.gz

in my case location is – /home/ruzdi/program/ns-allinone-2.34

step3 : Using command line go to this folder /home/ruzdi/program/ns-allinone-2.34

step4 : use the following command

sudo apt-get install build-essential autoconf automake libxmu-dev gcc-4.3 

step5 : change the following line in ns-allinone-2.34/otcl-1.13/Makefile.in file

change CC= @CC@ to CC= gcc-4.3 

step6 : then install using

./install

Step7: Once the installation is successful without any errors, we need to add the path information to the file ~/.bashrc

  $ gedit   ~/.bashrc 

Step8: Add the following lines to the file ~/.bashrc

# LD_LIBRARY_PATH
OTCL_LIB=/home/ruzdi/program/ns-allinone-2.34/otcl-1.13
NS2_LIB=/home/ruzdi/program/ns-allinone-2.34/lib
X11_LIB=/usr/X11R6/lib
USR_LOCAL_LIB=/usr/local/lib
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$OTCL_LIB:$NS2_LIB:$X11_LIB:$USR_LOCAL_LIB

# TCL_LIBRARY

TCL_LIB=/home/ruzdi/program/ns-allinone-2.34/tcl8.4.18/library
USR_LIB=/usr/lib
export TCL_LIBRARY=$TCL_LIB:$USR_LIB

# PATH

XGRAPH=/home/ruzdi/program/ns-allinone-2.34/bin:/home/ruzdi/program/ns-allinone-2.34/tcl8.4.18/unix:/home/ruzdi/program/ns-allinone-2.34/tk8.4.18/unix

# Note: the above two lines starting from XGRAPH should come in the same line

NS=/home/ruzdi/program/ns-allinone-2.34/ns-2.34/
NAM=/home/ruzdi/program/ns-allinone-2.34/nam-1.14/
PATH=$PATH:$XGRAPH:$NS:$NAM

Here replace /home/ruzdi/program/ with the path to your ns2 folder path.

Step9: For the changes to take effect immediately, do the following:

$ source      ~/.bashrc 

10. nw use the ‘ns’ command to check that it is installed correctly or not if your ns2 is instaled correctly then it show % sign . You can exit from this using ‘exxit’ command

Thats all cheers …

This post is written with the help of two blog post —

link1

link2

Simple solution to complex where clause brace problen in Code-igniter


In Code-Igniter How do you make a query with where clause with a brace like following —

SELECT * FROM props 
WHERE `active` = 1
AND (rent >= 25 OR price >=25) AND 1=  1
AND `props`.`id` = '1'

Code-Igniter active record pattern does not generally support this type of query as far i searched.

I found a surprising solution for this type of query. for this query i make the where clause like following —

$this->db->where('(rent >= 25 OR price >=25) AND 1= ',1); 
$this->db->where('props.id',1); 

Which does the tricks.

I don’t actually know this is the fault of the developers or a feature but it is good for my work to move on.

so the total query for this SQL becomes —

$this->db->where('(rent >= 25 OR price >=25) AND 1= ',1); 
$this->db->where('props.id',1); 
$this->db->get('props');

cheers………

Simple solution to Fast duplicate key press problem on keyboard in Ubuntu10.10


In my Ubuntu10.10 suddenly got some problem. The problem is that —

When i was pressing duplicate key very fast then it accepts only the fast key and escape the other duplicate keys. Such as if i type “http://” then it write “htp:/”, “teen” becomes “ten” etc.

To solve this problem go to

System->Preferences->Keybord
Then go to “accessibility” tab and uncheck the “Ignore fast duplicate keypresses” under “Bounce Keys” section.

Keybord-Accessibility

Keybord-Accessibility

Thats it…

Simple solution to android when running on ubuntu 10.10 – Failed to get the adb version: Cannot run program: java.io.IOException: error=2, No such file or directory


After installing android i got some problem when i was going to create a project and problem is —

Failed to get the adb version: Cannot run program “/usr/src/android-sdk-linux_x86/tools/adb”: java.io.IOException: error=2, No such file or directory

After that 
1. download getlibs from http://frozenfox.freehostia.com/cappy/getlibs-all.deb
2. open terminal and go to your download folder where getlibs-all.deb is placed 
3. then on terminal use the following command —      

getlibs aapt

How to login ubuntu as root user


here the tricks of how to login ubuntu as root user…
Open the terminal and type:

sudo passwd root

When you see the prompt that says “Enter new UNIX password”, enter the password you want for the root user and confirm it.
Save the file.

Click other and type your user name: root, and enter the password of root you have set.

Thats it ………
***Note this is a bad Idea to do if you are connected to the Internet while logged in as root. Any malicious scripts execute themselves with out user permissions.

Browse folder as root user on Ubuntu


Open you terminal and use the following command which will open a 
new window that one allow you to browse folder as root user—

gksudo nautilus

Changing default apache page on Ubuntu


Open your Apache configuration file httpd.conf

on ubuntu it is in /etc/apache2/httpd.conf and open it using

sudo gedit /etc/apache2/httpd.conf

then put your desired filename on directory index—

DirectoryIndex index.html index.htm default.htm index.php index.pl

Changing default apache page on Ubuntu

Open your Apache configuration file httpd.conf

on ubuntu it is in /etc/apache2/httpd.conf and open it using

sudo gedit /etc/apache2/httpd.conf

then put your desired filename on directory index—

DirectoryIndex index.html index.htm default.htm index.php index.pl

Changing English date format to Bangla date format


i use here the following function to change English date format to Bangla date format when displaying —-


<?php
function getBanglaDate($date){
 $engArray = array(
 1,2,3,4,5,6,7,8,9,0,
 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December',
 'am', 'pm'
 );
 $bangArray = array(
 '১','২','৩','৪','৫','৬','৭','৮','৯','০',
 'জানুয়ারি', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর',
 'সকাল', 'দুপুর'
 );

 $converted = str_replace($engArray, $bangArray, $date);
 return $converted;
}

?>

calling procedure is like —


<?php

 if($GLOBALS['lang'] == "bn"){
 $date = date( 'j F, Y, a g:i',strtotime($publisheddate) ) ;
 $date = getBanglaDate($date);
 }else if($GLOBALS['lang'] == "en"){
 $date = date( 'j F, Y, g:i a',strtotime($publisheddate) ) ;
 }
 ?>

So when if send a date format like  “28 July, 2010, 12:00 am”  then it returns   “২৮ জুলাই, ২০১০, সকাল ১২:০০”    date format

Cheers………

Simple steps to setting up virtual host host on Ubuntu Server


Virtual host is a virtual environment over the top of your current web server to simulate a separate hosting environment. Using virtual host you can enable site specific features and keep your development environment totally separate from another one.

For tutorial you need to mod_rewrite enabled.

Step 1: setup hosts file

open /etc/hosts and add a virtual domain with a specific local IP.

Lets assume that our virtual domain name is “ruzdi.com” and It will listen to the ip “127.0.0.2″

so on /etc/hosts file we will add

127.0.0.2 ruzdi.com

now whenever you browse http://ruzdi.com your browser will actually hit http://127.0.0.2

Step2: configure virtual host with apache
Now goto /etc/apache2/sites-available and create a file named “ruzdi.com

sudo touch ruzdi
sudo gedit /etc/apache2/sites-available/ruzdi

write the following contents inside. but please note to create the appropriate directory before linking your virtual host with that, for example we’ve create a folder named “/var/opt/ruzdi” and linked that directory as my document root in the following configuration file.



<VirtualHost 127.0.0.2:80>
        ServerName  ruzdi.com
        ServerAlias  ruzdi.com
        ServerAdmin admin@ruzdi.com
        DocumentRoot /opt/ruzdi
        <Directory /opt/ruzdi/>
                Options FollowSymLinks
                AllowOverride All
        </Directory>

</VirtualHost>

now create a symbolic link of this file to /etc/apache2/sites-enabled directory as “ruzdi.com

sudo ln -s /etc/apache2/sites-available/ruzdi /etc/apache2/sites-enabled/ruzdi

**** here look directory location is /opt/ruzdi so you must create a directory named “ruzdi” on /opt location

Step 3: restart apache

simple, either one of the followings

sudo a2ensite ruzdi

And

sudo /etc/init.d/apache2 restart

now on your browser to http:// ruzdi.com

***This is post is similar Hasin Hyder blog post I just change a little. In my case on the hosts file port was not working so I removed it and I got everything all right.

source :

Apache

Hasin Hyder

Setting up zend framework on ubuntu server


Now i am going to install the Zend Framework. Download the most recent version from the Zend Framework website and extract it to the /opt folder.

To enable us to easily switch out different versions, we will create a symbolic link to this folder (just right click and select the ‘Make link’ option and name it ‘zend’ and place it to your favourite location in my case I placed it to /var/www/ )

Next, we will tell php to include the zend framework in the include_path.


sudo gedit /etc/php5/apache2/php.ini

Add/Change the include_path in to :


include_path = ".:/var/www/zend/library"

Note that I used the symbolic link in the include path.. This way, when there is a new version of ZF, we can just switch out the symlink without having to edit the ini file!

In order to use the zend framework command line tool (/var/www/zend/bin/zf.sh), we need to install the php command line interface (php5-cli).


sudo apt-get install php5-cli

Note that the CLI uses a different version of the php.ini file (NOT the one in the apache2 folder but in the cli folder!). We need to tell CLI also where the zend framework directory is located.


sudo gedit /etc/php5/cli/php.ini

and set:


include_path = ".:/var/www/zend/library"

The final step is to include the path to /opt/Zend/bin in the unix PATH variable (this way, you can use zf.sh instead of /var/www/ zend/bin/zf.sh). use the following command .

sudo gedit ~/.bashrc

Add the following line at the end:


PATH=/var/www/zend/bin:”${PATH}”

The Zend Framework relies on the apache “rewrite” module. So, go ahead and enable the “rewrite” module using the following command:


sudo a2enmod rewrite

Restart apache..


sudo /etc/init.d/apache2 restart

and you should be all set

Simple steps to Installing Xdebug on Ubuntu Server


First install pear


sudo apt-get install php5-dev php-pear

Now install xdebug thru PECL.


sudo pecl install xdebug

Now we need to find where xdebug.so went (the compiled module)


find / -name 'xdebug.so' 2> /dev/null /usr/lib/php5/20090626/xdebug.so

20090626 is for my case it might be different for you

Then edit php.ini


sudo gedit /etc/php5/apache2/php.ini

Add the following line:


zend_extension="/usr/lib/php5/20090626/xdebug.so"

Then restart apache


sudo /etc/init.d/apache2 restart

for changes to take effect.


sudo /etc/init.d/apache2 restart

For checking it is install or not —

create a file on /var/www/  as info.php

and open it

sudo gedit /var/www/info.php

and write —

<?php
phpinfo();
?>

Now we call that file in a browser (e.g. http://localhost/info.php):

Xdebug Test

Xdebug Test

Cheers ………

Simple steps to install Apache, MySql , PHP (LAMP) and PhpMyAdmin On Ubuntu Server


Install mysql :

First we install MySQL 5 like this:

sudo apt-get install mysql-server mysql-client

You will be asked to provide a password for the MySQL root user – this password is valid for the user root@localhost as well as root@server1.example.com, so we don’t have to specify a MySQL root password manually later on:

New password for the MySQL “root” user: <– yourrootsqlpassword
Repeat password for the MySQL “root” user: <– yourrootsqlpassword

Install apache:

Apache2 is available as an Ubuntu package, therefore we can install it like this:


sudo apt-get install apache2

Now direct your browser to http://localhost/ and you should see the Apache2 placeholder page (It works!):

Apache Test

Apache Test

Apache’s default document root is /var/www on Ubuntu, and the configuration file is /etc/apache2/apache2.conf. Additional configurations are stored in subdirectories of the /etc/apache2 directory such as /etc/apache2/mods-enabled (for Apache modules), /etc/apache2/sites-enabled (for virtual hosts), and /etc/apache2/conf.d.

Install php:

We can install PHP5 and the Apache PHP5 module as follows:


sudo apt-get install php5 libapache2-mod-php5

We must restart Apache afterwards:


sudo /etc/init.d/apache2 restart

Testing PHP5 / Getting Details About Your PHP5 Installation

The document root of the default web site is /var/www. We will now create a small PHP file (info.php) in that directory and call it in a browser. The file will display lots of useful details about our PHP installation, such as the installed PHP version.


sudo gedit /var/www/info.php

and write —

<?php
phpinfo();
?>

Now we call that file in a browser (e.g. http://localhost/info.php):

PHP Test

PHP Test

As you see, PHP5 is working, and it’s working through the Apache 2.0 Handler, as shown in the Server API line. If you scroll further down, you will see all modules that are already enabled in PHP5. MySQL is not listed there which means we don’t have MySQL support in PHP5 yet.

Getting MySQL Support In PHP5

To get MySQL support in PHP, we can install the php5-mysql package. It’s a good idea to install some other PHP5 modules as well as you might need them for your applications. You can search for available PHP5 modules like this:

sudo aptitude search php5

Pick the ones you need and install them like this:

sudo apt-get install php5-mysql php5-curl php5-gd php5-idn php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-mhash php5-ming php5-ps php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl php5-json

Now restart Apache2:

sudo /etc/init.d/apache2 restart

Now reload http://localhost/info.php in your browser and scroll down to the modules section again. You should now find lots of new modules there, including the MySQL module.

Install php gd library :


sudo apt-get install php5-gd

Enable rewrite module

sudo a2enmod rewrite

Now restart Apache2:


sudo /etc/init.d/apache2 restart

Cnage apache settings —

Run the followint command

sudo gedit /etc/apache2/sites-enabled/000-default

then change –


<Directory /var/www/>

Options Indexes FollowSymLinks MultiViews

AllowOverride None

Order allow,deny

allow from all

</Directory>

to


<Directory /var/www/>

Options Indexes FollowSymLinks MultiViews

AllowOverride all

Order allow,deny

allow from all

</Directory>

install  phpMyAdmin

PhpMyAdmin  is a web interface through which you can manage your MySQL databases. It’s a good idea to install it:

sudo apt-get install phpmyadmin

You will see the following questions:

Web server to reconfigure automatically: <– apache2
Configure database for phpmyadmin with dbconfig-common? <– No

Afterwards, you can access phpMyAdmin under http://localhost/phpmyadmin/:

Phpmyadmin Test

Phpmyadmin Test

Only 10 easy steps to install Memcached Server and access it with PHP


Running You First Application using Memcached Server  thats good you are in right place ———

memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load.

memcached is meant to work in concert with something like the MySQL query cache, not replace it. The two implementations excel at vastly different things: memcached is an object cache, while MySQL provides a query cache.

memcached is extremely fast. It uses libevent, which provides a mechanism to execute a callback function when a specific event occurs on a file descriptor, to scale to any number of open connections. On a modern Linux system memcached utilizes epoll, is completely non-blocking for network I/O, ensures memory never gets fragmented, and uses its own slab allocator and hash table to achieve 0(1) virtual memory allocation.

Memcache consists of two parts; a server library which runs the caching daemon and a client library which allows PHP to interact with the server. The server library is called memcached and it depends on the libevent library, so the first step in the installation process is getting a recent copy of libevent.

Hi this time i am introducing cahching using memchache Server with some easy steps—

***** Remember for ubuntu users if any command does not support or running on command line then goto

System->Administration->Synaptic Package Manager and search by the package name and install

Step1: Install libevent

on fedora


yum install libevent

yum install libmemcached libmemcached-devel

or on ubuntu


sudo apt-get install libevent

sudo apt-get libmemcached libmemcached-devel

Step 2: Install Memcached Server

on fedora


yum install memcached

or on ubuntu


sudo apt-get install memcached

Step 3: Start Memcached server


memcached -d -m 512 -l 127.0.0.1 -p 11211 -u nobody

(d = daemon, m = memory, u = user, l = IP to listen to, p = port)

Step 4: Check your memcached server is running successfully


ps -eaf | grep memcached

Testing the memcached daemon with telnet

Step 5:Connect Memcached server via telnet


telnet 127.0.0.1 11211

Step 6: Check current status of Memcached Server on telnet prompt


stats

Step 7: Exit telnet


quit

Step 8: Install PHP client to access Memcached Server

if do not have pear install then first intall pear package —-

on fedora

</pre>
yum <em>install php</em>-<em>pear </em>(if pear is already this command is not necessary)
<pre>

on ubuntu


sudo apt-get install php-pear  (if pear is already this command is not necessary)

then

pecl install memcache

or

sudo pecl install memcache

It will make “memcache.so”,

you have add a line


extension=memcache.so

on your

/etc/php.ini

or

sudo gedit /etc/php5/apache2/php.ini

file

Step 9: Restart your apache server

on fedora


service httpd restart

or on ubuntu


sudo /etc/init.d/apache2 restart

Check your php info

create a file info.php on your local server and write

</pre>
echo phpinfo();
<pre>

then run on the browser you will find ————-

http://localhost/info.php

Memcache Image

Memcache Image

Step 10: Open your favorite editor to write the following code and execute it, it will cache your data into Memcached server and access it back for you


<?php

$memcache = new Memcache;

$memcache->connect('127.0.0.1', 11211) or die ("Could not connect"); //connect to memcached server

$mydata = "Chache me Ruzdi"; //string to be cached

$memcache->set('ruzdi', $mydata, false, 100); //add the data to memcached server

$cacheData = $memcache->get('ruzdi'); //retrieve your data from memcache server

var_dump($cacheData); //dump you data which is retrived from memcached server

?>

Cheers …….

This is written with the help of following site——–

link1

link2

link3

How to stop submit from on pressing enter key.


Key code of enter is 13 . so when we need to stop the enter from a text
field we just need to to trace the keypress event and stop for submittion.
Look carefully if condition of stopEnter function–
1> (evt.keyCode == 13) is the checking for enter key is pressed or not
2> (node.type == “text”) is the checking for enter key is pressed on text field or not
3> (node.name == “one”) is the checking for name of field is one or not
<?php    if($_POST){
        echo "Hit Enter";
    }
?>
<html>
    <head>
 <script language="javascript" type="text/javascript">
        function stopEnter(evt) {
            var evt = (evt) ? evt : ((event) ? event : null);
            var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
            if ((evt.keyCode == 13) && (node.type == "text") && (node.name == "one")) {
                return false;
            }
        }
        document.onkeypress = stopEnter;
    </script>

    </head>
    <body>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
            <input type="text" name="one"/>
            <input type="submit" />
        </form>
    </body>
</html>

How to avoid conflict between JQuery and Prototype or other JavaScript library


If a page has both JQuery and Prototype then I got conflict. There is a option to disable $ sign for JQuery so there is no conflict. I have used jq keyword for JQuery instead of $.


<script type="text/javascript" src="js/jquery-1.4.2.js"></script>

<script>
var jq = jQuery.noConflict();
</script>

Thats it

Javascript Loader String using JQuery


For javascript loader string —
1> first add the jquery library

<script type="text/javascript" src="js/jquery-1.4.2.js"></script>

2> Add the following loader script —-

<script type="text/javascript">
var loadCounter = 0;                        //counter of dots
var loadStrSuffix = "";                     //set the initial dosts to null
var noOfLoaderDots = 5;                     //no of dost will shown on loader string
var miliSecondsToUpdateLoaderDots = 800;    //update time of loader string in miliseconds
var sivar;                                  //sivar is use as the carrier of set interval function
/*
* function : enableLoader is used for enabling the loader
* args:
*  id- is the id of updated string location
*/
var enableLoader = function(id){
$('#'+id).css('display', 'block');
sivar = setInterval("updateLoaderStr('"+id+"')",miliSecondsToUpdateLoaderDots); // call 'updateLoaderStr()' function on every 'miliSecondsToUpdateLoaderDots' miliseconds and store this call into a variable sivar';
}
/*
* function : disableLoader is used for disabling the loader
* args:
*  id- is the id of updated string location
*/
var disableLoader = function (id){
$('#'+id).css('display', 'none');   //block the display of loader string
clearInterval(sivar);               //unset the call of set interval
}
/*
* function : updateLoaderStr is used for updating string
* args:
*  id- is the id of updated string location
*/
var updateLoaderStr = function(id){
if((loadCounter%(noOfLoaderDots+1))==0){
loadStrSuffix = '';
loadCounter++;
}else{
loadStrSuffix += '.';
loadCounter++;
}
$('#'+id).text('Loading'+loadStrSuffix);
}
</script>

3>then call this loader whenever you need. you may use different event here i used onclick event of button ————

<input type="button" value="enable" onclick="enableLoader('my_loader_id');">
<input type="button" value="disable" onclick="disableLoader('my_loader_id')">
<span id="my_loader_id" style="display:none">Loading...</span>

Thats it………….

A Database Class with Create, Read, Update And Delete operation using PHP Data Object ( PDO ) with Prepared Statement.


PDO stands for PHP Data Objects. It is developed to provide a lightweight interface for different database engines. And one of the very good features of PDO is that it works like a Data Access Layer so that you can use the same function names for all database engines. You can connect to different databases using DSN (Data Source Name) strings.
And some advantages of using prepared statements:
1>Better Performance
2>Prevention of SQL injection
3>Saving memory while handling blobs

<!––
– Create Database: `news`
– Then run the following sql
–

CREATE TABLE IF NOT EXISTS `articles` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title_en` varchar(250) DEFAULT NULL,
`title_bn` varchar(250) DEFAULT NULL,
`description_en` text,
`description_bn` text,
`image` varchar(50) DEFAULT NULL,
`published` timestamp NULL DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`active` tinyint(1) NOT NULL DEFAULT ‘1′ COMMENT ‘0=>retire, 
1=>active’,
`category_id` int(11) unsigned NOT NULL COMMENT ‘refer to id field of 
categories table’,
`user_id` int(11) unsigned NOT NULL COMMENT ‘refer to id field of user 
table’,
PRIMARY KEY (`id`),
KEY `published` (`published`,`active`,`category_id`),
KEY `user_id` (`user_id`),
KEY `fk_articles_categories_relation` (`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

–
– Dumping data for table `articles`
–

INSERT INTO `articles` (`id`, `title_en`, `title_bn`, 
`description_en`, `description_bn`, `image`, `published`, `created`, 
`active`, `category_id`, `user_id`) VALUES
(1, ‘test’, ‘test’, ‘test’, ‘test’, ‘test’, ‘2010-03-10 00:16:50′, 
‘2010-03-10 00:16:50′, 1, 1, 1),
(2, ‘test2′, ‘test2′, ‘test-desc2′, ‘test-desc2′, ‘test2′, ‘2010-03-19 
19:21:39′, ‘2010-03-19 19:21:39′, 1, 1, 1),
(3, ‘Upsate WOW Sunny Morning22!!!’, ‘Update WOW Dark Morning22!!!’, 
‘description_en’, ‘description_bn’, ‘image’, ‘2010-03-10 00:16:50′, 
‘2010-03-10 00:16:50′, 1, 1, 1);

–>

<?php
/*
* in my config file i defined following things
*/

//Database Connection

/*
* @DSN: It means Data Sourse Name . Here i am connecting my database to 
mysql database so my DSN is defined as following.
*   few properties are —
*
*
*   @host: default localhost. if it it on live server then use your 
liveserver hostnam
*        such as https://ruzdi.wordpress.com/
*   @dbname: name of your database.
*/
define(‘DSN’,'mysql:host=localhost;dbname=news’);

/*
*
* @USERNAME : name of database user here my databasee user name is root.
*/
define(‘USERNAME’,'root’);

/*
* @PASSWORD : name of database user password here my databasee user 
password is root.
*/
define(‘PASSWORD’,'root’);

?>

<?php

/*
* @author Ruzdi
*
*
* @class : This is the Abstract DB class this clss is responsible for 
connecting with database .
*/
abstract class DB{

/*
*@function: This is the the function which is responsible for connecting
 with database.
*
* @arguments: null
* @return : connection link.
*/
public function connectMySql(){

$dsn = DSN;
$user = USERNAME;
$password = PASSWORD;
try{
$pdoLink = new PDO($dsn, $user, $password);
}catch(PDOException $e){
echo ‘Connection Failed :: ‘.$e->getMessage();
return false;
}
return $pdoLink;
}

}

/*
* @author Ruzdi
*
*
* @class : This is the Articles class this clss is responsible for 
create, read, update and delete funtionalities with database using PHP 
Data Object ( PDO ) with Prepared Statement.
*/

class Articles extends DB {
private $pdo;
public  $result;

public function __construct(){}

/*
* @function: This is the the function which is responsible for viewing a
single articles.
*
* @arguments: $id: id of the article
* @return : single stdClass Object array.
*/

public function showArticle($id){

try {
$this->pdo = $this->connectMySql();

$query = ‘SELECT
id, title_en, title_bn,
description_en, description_bn,
image, published, created, active,
category_id, user_id
FROM
articles
WHERE
id =:id’;

$stmt = $this->pdo->prepare($query);

$stmt->bindParam(‘:id’,$id, PDO::PARAM_INT);

if(!$stmt->execute()){
return false;
}

$nart = $stmt->rowCount();

if ($nart == 0) {
return “No Article found on id “.$id;
}

$this->result = $stmt->fetch(PDO::FETCH_OBJ);

$this->pdo = null;

return $this->result;

} catch (PDOException $e) {
print “Error!: ” . $e->getMessage() . “<br/>”;

}
return NULL;
}

/*
* @function: This is the the function which is responsible for viewing 
all articles.
*
* @arguments: null
* @return : array of stdClass Object array.
*/

public function showArticles(){

try {
$this->pdo = $this->connectMySql();

$query = ‘SELECT
id, title_en, title_bn,
description_en, description_bn,
image, published, created, active,
category_id, user_id
FROM
articles
ORDER BY
id DESC’;

$stmt = $this->pdo->prepare($query);

if(!$stmt->execute()){
return false;
}

$nart = $stmt->rowCount();

if ($nart == 0) {
return “No Article Found”;
}

$this->result = array(‘count’=>$nart, 
‘result’=>$stmt->fetchAll(PDO::FETCH_OBJ));

$this->pdo = null;

return $this->result;

} catch (PDOException $e) {
print “Error!: ” . $e->getMessage() . “<br/>”;

}
return NULL;
}

/*
* @function: This is the the function which is responsible for inserting
 articles.
*
* @arguments: $params: it is an array where fields are as key of the 
array and the value of the array are corresponding fields value.
*                  example: $params['title_en']=”Title” here “title_en” 
is the field name of the table and “Title” is the value of the field.
* @return : boolean true for successfully inseerted false for insertion 
failed.
*/

public function insertArticle($params){

try {
$this->pdo = $this->connectMySql();

$query = ‘INSERT
INTO articles
SET
title_en = :title_en,
title_bn = :title_bn,
description_en = :description_en,
description_bn = :description_bn,
image = :image,
published=:published,
created=:created,
active=:active,
category_id=:category_id,
user_id=:user_id’;

$stmt = $this->pdo->prepare($query);

$stmt->bindParam(‘:title_en’,$params['title_en'], 
PDO::PARAM_STR);  // PDO::PARAM_STR is used for treating 
$params['title_en'] as String
$stmt->bindParam(‘:title_bn’,$params['title_bn'], PDO::PARAM_STR);
$stmt->bindParam(‘:description_en’,$params['description_en'], 
PDO::PARAM_STR);
$stmt->bindParam(‘:description_bn’,$params['description_bn'], 
PDO::PARAM_STR);
$stmt->bindParam(‘:image’,$params['image'], PDO::PARAM_STR);
$stmt->bindParam(‘:published’,$params['published'], PDO::PARAM_STR);
$stmt->bindParam(‘:created’,$params['created'], PDO::PARAM_STR);
$stmt->bindParam(‘:active’,$params['active'], PDO::PARAM_INT);      
// PDO::PARAM_INT is used for treating $params['active'] as Integer
$stmt->bindParam(‘:category_id’,$params['category_id'], 
PDO::PARAM_INT);
$stmt->bindParam(‘:user_id’,$params['user_id'], PDO::PARAM_INT);

if(!$stmt->execute()){
return false;
}

$this->pdo = null;

return true;

} catch (PDOException $e) {
print “Article insertion is failed !: ” . $e->getMessage() . 
“<br/>”;
return false;
}

}

/*
* @function: This is the the function which is responsible for updating 
articles.
*
* @arguments: $params: it is an array where fields are as key of the 
array and the value of the array are corresponding fields value.
*                  AND $params['id'] is the id of table which need to be
 updated.
*                  example: $params['title_en']=”Title” here “title_en” 
is the field name of the table and “Title” is the value of the field.
* @return : boolean true for successfully updated false for update 
failed.
*/
public function updateArticle($params){

try {
$this->pdo = $this->connectMySql();

$query = “UPDATE
articles
SET
title_en = :title_en,
title_bn = :title_bn

WHERE
id=:id” ;

$stmt = $this->pdo->prepare($query);

$stmt->bindParam(‘:id’,$params['id'], PDO::PARAM_INT);

$stmt->bindParam(‘:title_en’,$params['title_en'], PDO::PARAM_STR);
$stmt->bindParam(‘:title_bn’,$params['title_bn'], PDO::PARAM_STR);

if(!$stmt->execute()){
return false;
}

$this->pdo = null;
return true;

} catch (PDOException $e) {
print “Article update failed !: ” . $e->getMessage() . “<br/>”;
return false;
}

}

/*
* @function: This is the the function which is responsible for deleting 
articles.
*
* @arguments: $id: This is the id of the row which need to be deleted .
* @return : boolean true for successfully deleted false for delete 
failed.
*/

public function deleteArticle($id){

try {
$this->pdo = $this->connectMySql();
$query = “DELETE FROM
articles
WHERE
id=:id” ;
$stmt = $this->pdo->prepare($query);
$stmt->bindParam(‘:id’,$id, PDO::PARAM_INT);
if(!$stmt->execute()){
return false;
}
$this->pdo = null;

} catch (PDOException $e) {
print “Article delete failed !: ” . $e->getMessage() . “<br/>”;
return false;
}

return true;
}

}

$articles = new Articles();

/*
* For showing all articles
*/

/*
*
$result = $articles->showArticles();
echo “<pre>”;
print_r($result);
echo “</pre>”;

echo $result['result'][0]->title_bn;

*
*/

/***
* For  single article
*/

/*
*
*
$result = $articles->showArticle(5);
echo “<pre>”;
print_r($result);
echo “</pre>”;
echo $result->title_en;
*/

/*
*
* For inserting article
*/
/*
$params = array(
‘title_en’ => ‘WOW Sunny Morning3!!!’,
‘title_bn’ => ‘WOW Dark Morning3!!!’,
‘description_en’ => ‘description_en’,
‘description_bn’ => ‘description_bn’,
‘image’ =>’image’,
‘published’=>’2010-03-10 00:16:50′,
‘created’=>’2010-03-10 00:16:50′,
‘active’=>1,
‘category_id’=>1,
‘user_id’=>1
);

if ($articles->insertArticle($params)) {
echo “Successfully Article Inserted”;
}else{
echo “Article Insertion is Failed “;
}*/

/*
*
* For updating article
*/

/*
$params = array(
‘id’=>3,
‘title_en’ => ‘Upsate WOW Sunny Morning22!!!’,
‘title_bn’ => ‘Update WOW Dark Morning22!!!’

);

if ($articles->updateArticle($params)) {
echo “Successfully Article Updated”;
}else{
echo “Article Update is Failed “;
}
*/

/*
*
* For delete an article
*/

/*if($articles->deleteArticle(1)){
echo “Successfully article deleted”;
}else{
echo “Article delete failed “;
}*/

<span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">
<pre style="font: normal normal normal 12px/18px Consolas, Monaco, 'Courier New', Courier, monospace;">

How to Image Store and Update on database and view stored image from database using Cakephp ?


1> create a database table as follows.

— Table structure for table `users`

CREATE TABLE IF NOT EXISTS `users` (

`id` int(11) unsigned NOT NULL AUTO_INCREMENT,

`name` varchar(100) DEFAULT NULL,

`email` varchar(150) DEFAULT NULL,

`firstname` varchar(60) DEFAULT NULL,

`lastname` varchar(60) DEFAULT NULL,

`img_name` varchar(25) NOT NULL,

`image` blob NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;

2> create a model on your app/models folder

//model for the abave table

class User extends AppModel {

var $name = ‘User’;

var $hasMany = array(‘Post’);

}

3> create a controller as following on app/controllers folder.

//my TestUsers controller

class TestUsersController extends Controller {

var $name = ‘TestUsers’;

var $uses = array(‘User’);

var $helpers = array(‘Html’, ‘Form’);

var $components = null;

/*

* method: This method is for upload and store an image to database table.

* @arguments: null

* @return: null

*/

function add(){

if($this->data &&is_uploaded_file($this->data[‘File’][‘image’][‘tmp_name’]) ){

$this->data[‘User’][‘img_name’] = $this->data[‘File’][‘image’][‘name’];

$fileData = fread(

fopen($this->data[‘File’][‘image’][‘tmp_name’], “r”),

$this->data[‘File’][‘image’][‘size’]

);

$this->data[‘User’][‘image’] = $fileData;

if($this->User->save($this->data[‘User’])){

echo “File uploaded successfully”;

}else{

echo “File does not uploaded successfully”;

}

}

}

/*

* method: This method is for edit the uploaded and stored image to database table and show the upload image from database.

* @arguments: null

* @return: null

*/

function edit($id=null){

if($this->data &&is_uploaded_file($this->data[‘File’][‘image’][‘tmp_name’]) ){

$this->data[‘User’][‘img_name’] = $this->data[‘File’][‘image’][‘name’];

$fileData = fread(

fopen($this->data[‘File’][‘image’][‘tmp_name’], “r”),

$this->data[‘File’][‘image’][‘size’]

);

$this->data[‘User’][‘image’] = $fileData;

if($this->User->save($this->data[‘User’])){

echo “File uploaded successfully”;

}else{

echo “File does not uploaded successfully”;

}

}else{

$this->data = $this->User->read(null,$id);

}

}

/*

* method: this method is for retrive the image from database.

* this is action will be on your image sourse.

* (here it is : project_nam/TestUsers/image)

* @arguments: null

* @arguments: null

*/

function image($id){

$this->data = $this->User->read(null,$id);

echo $this->data[‘User’][‘image’];

die;

}

}

4> create view add.ctp on app/views/test_users folder.

<?php e($form->create(‘User’,array(‘url’=>array(‘controller’=>’test_users’, ‘action’=>’add’), ‘type’ => ‘file’, ‘name’=>’test_user_form’))); ?>

<?php e($form->input(‘name’)); ?>

<?php e($form->input(’email’)); ?>

<?php e($form->input(‘firstname’)); ?>

<?php e($form->input(‘lastname’)); ?>

<?php e($form->file(‘File.image’)); ?>

<?php e($form->submit(‘submit’, array(‘style’=>’float:left’, ‘width’=>’100px’))); ?>

<?php e($form->end()); ?>

4> create view edit.ctp on app/views/test_users folder.

<?php e($form->create(‘User’,array(‘url’=>array(‘controller’=>’test_users’, ‘action’=>’add’), ‘type’ => ‘file’, ‘name’=>’test_user_form’))); ?>

<?php if(isset ($this->data[‘User’][‘image’])):?>

<img alt=”img” src=”http://localhost/mycake/test_users/image/&lt;?php echo $this->data[‘User’][‘id’]; ?>” />

<?php endif; ?>

<?php e($form->input(‘name’)); ?>

<?php e($form->input(’email’)); ?>

<?php e($form->input(‘firstname’)); ?>

<?php e($form->input(‘lastname’)); ?>

<?php e($form->file(‘File.image’)); ?>

<?php e($form->submit(‘submit’, array(‘style’=>’float:left’, ‘width’=>’100px’))); ?>

<?php e($form->hidden(‘id’)); ?>

<?php e($form->end()); ?>

now for image insert use:

http://localhost/project_name/test_users/add

for edit and view database image use.

http://localhost/project_name/test_users/edit/4

(here 4 is the id of users table )

Thats all

IMAP and POP3


What is IMAP and POP3?
Need IMAP or POP3 email hosting? Business Creator Pro has you covered. Click here for a free trial.

POP3 and IMAP are two different protocols used to access e-mail. POP3 and IMAP function very differently from each other and each has their own advantages. POP3 is useful for checking your e-mail from one computer at a single location. IMAP is the better option when you need to check your e-mail from multiple computers at different locations such as at work, home, or on the road.
POP3
POP3 works by accessing the inbox on the mail server and then downloading the new messages to your computer. With this type of account you do not have to stay logged on to the Internet. You can log on when you want to receive and send new messages. Once your new messages have been downloaded to your computer you can log off to read them. This option is good when you connect to the internet through a dial up service and are charged for your connection time.
IMAP
IMAP lets you view the headers of the new messages on the server and then retrieves the message you want to read when you click on them. When using IMAP, the mail is stored on the mail server. Unless you copy a message to a “Local Folder” the messages are never copied to your PC. Using this protocol, all your mail stays on the server in multiple folders, some of which you have created. This enables you to connect to any computer and see all your mail and mail folders. In general, IMAP is great if you have a dedicated connection to the internet or you like to check your mail from various locations.

It is important to point out that POP3 can be set to leave your e-mail on the server instead of downloading to your computer. This feature enables you to check your e-mail from multiple locations just like IMAP. So why choose IMAP rather than POP3 with the leave mail on server setting? With the POP3 leave mail on server setting only your e-mail messages are on the server, but with IMAP your e-mail folders are also on the server.

So in a nutshell the scenarios for using POP3 and IMAP can be summarized as follows…
When should I use POP3?
-When you only check e-mail from one computer at a single location.
-You want to remove your e-mail from the mail server.
-You connect to the internet through dial up and are charged for connection time.
When should I use IMAP?
-When you need to check e-mail from multiple computers at multiple locations.
-You use Web mail such as Gmail, Yahoo or Hotmail.
-You need to preserve the different e-mail folders you have created.
Tips for better performance
Keep your Inbox small! This is especially true for POP3 and will speed up your e-mail retrieval. Checking the e-mail is directly dependent on how many e-mail messages are in your inbox on the mail server.
POP3
– Try to reduce your inbox size. POP’ing large mail boxes consume excessive server resources.
– Set to remove mail from server at the end of every month or even sooner.
– Do not check your email more frequently than every 15 minutes.
IMAP
– Do NOT check all folders for new messages! This slows your e-mail substantially.
– Organize your mail into folders, and archive your older messages. This speeds up e-mail retrieval by minimizing the number of messages in the inbox.

How to submitting from inside of iFrame from Outside of iFrame


In case of situation like that a form which is inside of iframe but I  need to submit it from outside of iframe.

<iframe name=”displayframe” src=”display.php” width=”100%” height=”650px” style=’border:none’ >

<form action=”<?php echo $base_index.$action;?>” method=”post” enctype=”multipart/form-data” name=”formdisplay” id=”formwork”>
<input type=”hidden” id=’base’ value='<?php echo $base_index?>’ />

<table width=”522″ border=”0″ align=”center”>
<tr>
<td align=”right”><b>Title:</b></td>
<td colspan=”4″><label>
<input name=”title” type=”text” id=”title” size=”50″  />
</label></td>
</tr>
<tr>
<td align=”right”><b>Description:</b></td>
<td colspan=”4″><label>
<textarea name=”description” rows=”5″ cols=”30″ style=”width:600px” >
</textarea>
</label></td>
</tr>

</table>
</form>

</iframe>

<input type=”button” name=”insert” id=”button” onclick=”submitDisplayForm()” value=”submit” />

and my JavaScript code is

<script type=”text/javascript”>

window.frames[‘displayframe’].document.forms[‘formdisplay’].submit();

</script>

in this javascript code “displayframe” is the name of iframe and “formdisplay” is the name of form which is inside of iframe.

Thats all i have done so far.

Creating Image Border


<?php

/*

* This function is for creating image border . Here image1 is the full path of the

* image and border is the border size.

*

* This function returns the image which one is input with a definite image border

* defined by $border varible

*/

/*

* @author : ruzdi + (internet browsing help)

* @parameters : $image is full path of the image , $border is the border size

* @return : null

* @output : image1 will be replaced by the new image

*/

//THIS FUNCTION REPLACE OLD IMAGE BY THE NEW IMSGE AS THE NAME OF $image1 ON THE SAME FOLDER

function imageBorder($image1='image1.jpg',$border=10) {

$im = ImageCreateFromJpeg($image1);

$width = ImageSx($im);

$height = ImageSy($im);

$newimage_width = $width + ( 2*$border ); // this is the new width after adding border

$newimage_height = $height + ( 2*$border ); // this is the new height after adding border

$newimage = imagecreatetruecolor( $newimage_width, $newimage_height );

$border_color = imagecolorallocate( $newimage, 255, 255, 255 ); //here first paremeter is image name and next three are rgb value

imagefilledrectangle($newimage,0,0,$newimage_width,$newimage_height,$border_color);

imageCopyResized($newimage,$im,$border,$border,0,0,$width,$height,$width,$height);

ImageJpeg($newimage,$image1,100);

chmod($image1,0666);

}

/*

* This function is for creating image border . Here image1 is the full path of the

* image and border is the border size.

*

* This function returns the image which one is input with a definite image border

* defined by $border varible

*/

/*

* @author : ruzdi + (internet browsing help)

* @parameters : $image1 is full path of the image , $image2 new imagename, $border is the border size

* @return : null

* @output : A new $image2 will be created on the same folder

*/

//THIS FUNCTION PRODUCE NEW IMAGE AS THE NAME OF $image2 ON THE SAME FOLDER

function imageBorder2($image1='image1.jpg',$image2='image2.jpg',$border=0) {

$im = ImageCreateFromJpeg($image1);

$width = ImageSx($im);

$height = ImageSy($im);

$newimage_width = $width + ( 2*$border ); // this is the new width after adding border

$newimage_height = $height + ( 2*$border ); // this is the new height after adding border

$newimage = imagecreatetruecolor( $newimage_width, $newimage_height );

$border_color = imagecolorallocate( $newimage, 255, 255, 255 ); //here first paremeter is image name and next three are rgb value

imagefilledrectangle($newimage,0,0,$newimage_width,$newimage_height,$border_color);

imageCopyResized($newimage,$im,$border,$border,0,0,$width,$height,$width,$height);

ImageJpeg($newimage,$image2,100);

chmod($image2,0666);

}

imageBorder('replace.jpg',10);

imageBorder2('old.jpg','new.jpg',20);

?>;

click to download

Simple solution to complex where clause brace problen in Code-igniter


In Code-Igniter How do you make a query with where clause with a brace like following —

SELECT * FROM props 
WHERE `active` = 1
AND (rent >= 25 OR price >=25) AND 1=  1
AND `props`.`id` = '1'

Code-Igniter active record pattern does not generally support this type of query as far i searched.

I found a surprising solution for this type of query. for this query i make the where clause like following —

$this->db->where('(rent >= 25 OR price >=25) AND 1= ',1); 
$this->db->where('props.id',1); 

Which does the tricks.

I don’t actually know this is the fault of the developers or a feature but it is good for my work to move on.

so the total query for this SQL becomes —

$this->db->where('(rent >= 25 OR price >=25) AND 1= ',1); 
$this->db->where('props.id',1); 
$this->db->get('props');

cheers………