Here’s a easy way to create guestbook with php.

First you have to create database for it. If your database has been created add this table to database.


 CREATE TABLE IF NOT EXISTS `posts` (

 `name` varchar(100) NOT NULL,

 `email` varchar(100) NOT NULL,

 `website` varchar(100) NOT NULL,

 `message` text NOT NULL,

 `ip` varchar(25) NOT NULL,

 `date` varchar(50) NOT NULL

 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Step 1: Creating A Form

First we have to create a form. to do this use the following PHP code:

echo "<form action='index.php?act=add' method='post'>"

.”Name:
<input type=’text’ name=’name’ size=’30′ />

.”Email:
<input type=’text’ name=’email’ size=’30′ />

.”Website:
<input type=’text’ name=’website’ size=’30′ />

.”Message:
<textarea cols=’30′ rows=’8′ name=’message’></textarea>

.”<input type=’submit’ value=’Post’ />”

.”</form>”;

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Step 2: Add Info To Database

Now we have to add info to database. Do this using by this PHP code:


if($_GET['act'] == "add")

{ // If act is "add" like this file.php?act=add display the content

$sqlCon = mysql_connect(“localhost”, ”root”, ”bananaman”); // Connect to database

if($sqlCon == true){ // If connection has been made then..

$sqlSel = mysql_select_db(“guestbook”, $sqlCon); // Select a database

if($sqlSel == true)

{ // If database has been successfully selected gather info and post it

$name = addslashes(htmlspecialchars($_REQUEST['name'])); // Takes ”name” field from the form

$email = addslashes(htmlspecialchars($_REQUEST['email'])); // Takes ”email” field from the form

$website = addslashes(htmlspecialchars($_REQUEST['website'])); // Takes ”website” field from the form

$message = addslashes(htmlspecialchars($_REQUEST['message'])); // Takes ”message” field from the form

$ip = $_SERVER['REMOTE_ADDR']; // This takes user’s IP

$time = time(); // Get UNIX timestamp

// This will create a SQL query which inserts all that information into database

$sql = ”INSERT INTO posts (name, email, website, message, ip)

VALUES ('".$name."', '".$email."', '".$website."',

'".$message."', '".$ip."', '".$time."')";

// This will process SQL query and performs inserting info to database

$query = mysql_query($sql);

if($query == true) { // If everything was correct ..

echo ”Your post has been successfully posted!”; // Display a success message

}else { // But if there was something wrong ..

echo ”There was something wrong.”; // Display a fail message

// As you can see I have commented

// mysql_error() function. It is because

// if you want to see what went wrong with

// your SQL query. Displaying it is not very

// good idea because it’s like a candy to

// hackers. So if you have fixed the problem

// make sure to add comment ”//” in front of it

//echo mysql_error();

}

mysql_close($sqlCon); // Close connection to database

}else{

exit; // If database selection wasn’t a success close script

}

}else{

exit; // If connecting to database wasn’t a success close script

}

}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Step 3: Displaying Posts

Now posting part is done, now we’re going to display our posts.

Use this PHP code:

$sqlCon = mysql_connect("localhost", "root", "bananaman"); // Connect to database

if($sqlCon == true) { // If connecting was successful ..

$sqlSel = mysql_select_db(“guestbook”, $sqlCon); // select your database

if($sqlSel == true) { // If database selecting was successful then take info from it

// Select all records from database

$sql = ”SELECT * FROM posts”;

// Process your selection

$query = mysql_query($sql);

// This creates a table which contains all info

// of your posts

while($info = mysql_fetch_array($query)) {

echo ”<table width=’300′ border=’1′>”

.”<tr>”

.”<td>Posted by: <a href=’”.$info['website'].”‘>”.$info['name'].”</a> (<a href=’mailto:”.$info['email'].”‘>Email</a>)</td>”

.”<td align=’right’>”.date(“H:i j F Y”, $info['date']).”</td>”

.”</tr>”

.”<tr>”

.”<td colspan=’2′>”.$info['message'].”</td>”

.”</tr>”

.”</table>”

.”
“;

}

mysql_close($sqlCon); // Close database connection

}else { // If database selection wasn’t successful ..

exit; // exit form the script

}

}else { // If connection to database wasn’t success ..

exit; // exit from your script

}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

And you are done with your script. It should look like this:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Thank you!

If you try to install memcached with Linux server then use following commands

# yum install libevent
# yum install libmemcached libmemcached-devel
# yum install memcached

For Starting the memcached server
# memcached -d -m 512 -l 127.0.0.1 -p 11211 -u nobody

11211 port is default port for memcached server.

For using the memecached with php client you need to install following package

# pecl install memcache

After installing all packages restart the apache server.

# /etc/sbin/service httpd restart

<?php
/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$memcache_obj->set('any_key', 'some value', MEMCACHE_COMPRESSED, 50);
echo $memcache_obj->get('any_key');
?>

Important Note: Memcached key has limitations of 250 charactors, So key value should be with in 250 charactors.

Many PHP developers are been asked this question in interview. But many times they are not sure about answer.

There is no difference between die() and exit() function. They both are same and worked same.
Again question is why php keep the both functions if they are same. Both functions are alias of each other function.

Due to API and keeping the backward compatibility both functions are kept.

Here is one more example:

is_int() and is_integer() are also same.

There are quite a few functions in PHP which you can call with more than one name. In some cases there is no preferred name among the multiple ones, is_int() and is_integer() are equally good for example. However there are functions which changed names because of an API cleanup or some other reason and the old names are only kept as aliases for backward compatibility. It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script. This list is provided to help those who want to upgrade their old scripts to newer syntax.

Full list of Aliases function you will find on following URL:

http://php.net/manual/en/aliases.php

Sleep is very common method in every language. How sleep function works we need to understand.

Sleep function delays the program execution for the given number of seconds.
Usleep delays program execution for the given number of micro seconds.

Following is the php example with sleep function

<?php
echo date('h:i:s') . "<br />";

//stop execution for 30 seconds
sleep(30);

//start again
echo date('h:i:s');

?>

Following is the php example with usleep function

<?php
echo date('h:i:s') . "<br />";

//stop execution for 30 seconds
usleep(30000000);

//start again
echo date('h:i:s');
?>

In PHP language checking the logs and checking error is sometimes became difficult.
PHP is offer inbuild solution to log all errors to a log fiie.

First I will tell about creating the normal error log file.
Open your pho.ini file and modify the following line.

error_log = /var/log/php-error.log

Make sure display_errors set to Off (no errors to end users)

display_errors = Off

This is normal way to check the php error log.

But if you want to check where is script is dying or you want to debug.
Then use trigger_error() function. Personaly I love to use this function for logging the php errors.

Using this function you can specify the custom error messages as per your script requirement.

<?php
$test = ture;
if ($test == true) {
trigger_error("A custom error has been triggered");
}
?>

When you run this file and check the php error log file or you can check httpd/apache error log file.

you will got following error message.

Notice: A custom error has been triggered
in C:\webfolder\test.php on line 5

In daily development we face lot of cross browser issues and sometimes conditional css will never work as excepted.

In this article I will show how to detect IE browser and IE 7 and IE8 using php language.

Following function you can use for detecting the IE browsers.


function detect_ie($navigator_user_agent)
{
 if (stristr($navigator_user_agent, "MSIE"))
 {
 return true;
 } else return false;
}

detect_ie($_SERVER['HTTP_USER_AGENT']);

//detect IE7 browser

function detect_ie7($navigator_user_agent)
{
 if (stristr($navigator_user_agent, "msie 7"))
 {
 return true;
 } else return false;
}

detect_ie7($_SERVER['HTTP_USER_AGENT']);

function detect_ie8($navigator_user_agent)
 {
 if (stristr($navigator_user_agent, "msie 7"))
 {
 return true;
 } else return false;
 }

detect_ie8($_SERVER['HTTP_USER_AGENT']);

For this example I used the RHEL 5.3 edition. If server is new then use follwoing commands to keep server up to date.
When I tried to install php-pear lib in server I am not able to install all the pear libs. Then I Used following commands for installing the php-pear fully.

# yum update
# up2date -u
# yum install lighttpd-fastcgi php-cli php-mysql php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc php-eaccelerator php-magickwand php-magpierss php-mapserver php-mbstring php-mcrypt php-mhash php-mssql php-shout php-snmp php-soap php-tidy php-pear php-devel httpd-devel mysql-server mysql-devel

The 2 RPMs which we need are:
epel-release and remi-release

# wget http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-3.noarch.rpm
# rpm -Uvh epel-release-5-3.noarch.rpm

# wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
# rpm -Uvh remi-release-5.rpm

# yum install php-pear*

# /sbin/service httpd start
# /sbin/service mysqld start

# php -v

Many times we need to array has duplicate values or not. Using php language this is very easy.

For checking the duplicate array value array_unique function is very useful.

Here I am giving you very simple php example:


<?php
 $array1 = array("banana","apple","pear","banana");

 if (count(array_unique($array1)) < count($array1))
 echo 'Duplicate entry found in array';
 else
 echo 'No Duplicate values found in array';
 ?>

Output:  Duplicate entry found in array

Many times we got requirement of check file from specific directory. Following code will work in all the system like (Mac, Linux and Windows).

Using following php code you can check file is present or not in specific directory.


<?php
 $filename = '/var/www/html/test/test.txt';

 if (file_exists($filename)) {
 echo "The file $filename exists";
 } else {
 echo "The file $filename does not exist";
 }

?>

Use can use the strpos function for string to search in

<?php
$mystring = 'abc xyz';
$findme   = 'abc';
$check_string = strpos($mystring, $findme);

// because the position of 'a' was the 0th (first) character.
if ($check_string === false) {
 echo "The string '$findme' was not found in the string '$mystring'";
} else {
 echo "The string '$findme' was found in the string '$mystring'";
 echo " and exists at position $pos";
}
?>
Wordpressapi is developer code book.
wordpressapi on Facebook

Who am I?

Sony Kumari founded Wordpressapi in Feb 2010. She started writing since Aug 2006 in wordpress blog. Later on She moved her blog to wordpressapi.com.

Sony Kumari is dubble gradute and earned M.C.A. in Computers. Sony Kumari handled the so many projects in many different technology. She worked on Java, PHP, Ruby on Rails, Javascript, Web services, Social applications, Ad campaigns.

Mahesh is the Author of Wordpressapi, as well as a serial web entrepreneur, sci-fi author, and aspiring world changer. He has been writing for Wordpressapi since Dec 2009. His previous experience includes Photoshop Design, CSS design, Web design and wordpress themes development.

Mahesh is a graduate and earned a B.E. in Electronics. He is having three years of experience in Web design and Wordpress application development.

Rahul is the Author of Wordpressapi, as well as a web designer and photoshop artist. His previous experience includes Photoshop Design, CSS design, Web design and wordpress themes development.

Rahul is a graduate and earned a B.A. in History. He is having Five years of experience in Web design and Wordpress application development.

© 2010 Wordpressapi. All Rights Reserved. Reproduction without explicit permission is prohibited.