Thursday, November 3, 2011

Simple way to change the records order

Simple way to change the records order

Many times we have the need to change the table records order. Joomla is an example. In joomla, many modules has the feature to change the order of the records.

Here is an example of ordering the table records. Also added the code if we want to add a record into a particular position.

Assume that there is a table 'f_users' and it has fields like users_id,user_pos . We are considering this only :).

First of all, we are listing the records based on user_pos. And add the links for 'up' and 'down' .

Source code

<?php

// data base connection codes

extract($_GET);

// create a new user to the particular position

// ************ New user creation section starts *******************

if(isset($action))
{
// assume that the position is 5
$position = 5;
// increment the position by 1 if the user position is greater than 5
mysql_query("UPDATE f_users SET user_pos=user_pos+1 WHERE user_pos >= $position");
// inserting new user
mysql_query("insert into f_users(users_name,user_pos) values('blabla',$position)");
}
// ************ New user creation section enda *******************

if(isset($move))
{
switch($move)
{
case 'up':
// this has to move to top
$base = $id;
// find the top one
$prevOne = mysql_result(mysql_query("SELECT MAX(user_pos) FROM f_users WHERE user_pos < $base "),0);
// swapping the values

mysql_query("UPDATE f_users SET user_pos = CASE user_pos WHEN $base THEN $prevOne WHEN $prevOne THEN $base END WHERE user_pos IN ($base, $prevOne)");

break;
case 'down':
// this has to move down
$base = $id;
// find the bottom one
$nextOne = mysql_result(mysql_query("SELECT MIN(user_pos) FROM f_users WHERE user_pos > $base "),0);
// swapping the values
mysql_query("UPDATE f_users SET user_pos = CASE user_pos WHEN $base THEN $nextOne WHEN $nextOne THEN $base END WHERE user_pos IN ($base, $nextOne)");
break;
default:
break;
}
}

$first = mysql_result(mysql_query("SELECT MIN(user_pos) FROM f_users "),0);
$last = mysql_result(mysql_query("SELECT MAX(user_pos) FROM f_users "),0);
$res = mysql_query("select users_id,user_pos FROM f_users ORDER BY user_pos");
?>
</p>
<table width="26%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="18%">&nbsp;</td>
<td width="39%">&nbsp;</td>
<td width="43%">&nbsp;</td>
</tr>
<?php
while($row = mysql_fetch_array($res))
{
?>
<tr>
<td><?php echo $row['users_id']; ?></td>
<td><?php echo $row['user_pos']; ?></td>
<td>
<?php
if($row['user_pos']!=$first)
echo '<a href="?move=up&id='.$row['user_pos'].'">Up</a>';
?>
&nbsp;&nbsp;&nbsp;&nbsp;
<?php
if($row['user_pos']!=$last)
echo '<a href="?move=down&id='.$row['user_pos'].'">down</a>';
?>
</td>
</tr>
<?php
}
?>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><a href="?action=adduser">add user</a></td>
</tr>
</table>

Monday, August 29, 2011

JFolder::create: Could not create directory

JFolder::create: Could not create directory
Warning! – Failed to move file
Unable to find install package

If we get this error while installing a joomla plugin, it may because of the path in the configuration file. This issue is mainly when we are copying the joomla site into another domain and not changing the path of the configuration file.If the value of these variables are not existing path, the installation wont works. It may be absolute or relative path.

var $log_path = '/tmp';
var $tmp_path = '/var';

These two paths should be the existing paths.

Monday, March 14, 2011

How to select the timezone using php

In PHP we can find the server time using the date(). But it returns the time of the server where it located. If our website users are from different country we need to display the correct country time instead of server time. If we want to display the local time of a users browsing your webpage, we must find the timezone of the user. If we know the timezone we can find the time of the user timezone. We can list the timezones in a select box and if the user selects the timezone we can find the time of the timezone. In this example it shows how to get the user timezone times.

Step 1 : List the timezones
The 'DateTimeZone::listIdentifiers() ' function returns the timezones and we can iterate the timezones.
To get the timezones use the following code
<select id="timezone" name="timezone">
<?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
foreach( $timezone_identifiers as $value ){
if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $value ) ){
$ex=explode("/",$value);//obtain continent,city
if ($continent!=$ex[0]){
if ($continent!="") echo '</optgroup>';
echo '<optgroup label="'.$ex[0].'">';
}
$city=$ex[1];
$continent=$ex[0];
echo '<option value="'.$value.'">'.$city.'</option>';
$selected = '';
}
}
?>
</optgroup>
</select>

The above code will display the timezones in a select box. The user can select the corresponding timezone. It displays the timezones in the basis of continent. Each continental city is listed as groups.

Step 2: Submit the data and set the timezone

use <form> to submit the selected timezone and set the selected timezone as default timezone. use 'date_default_timezone_set' to set the timezone and get the time using time(). Now it will return the time of the new timezone.
<?php
date_default_timezone_set("$timezone"); // set the selected time zone
echo "<pre>";
print_r( getdate() );
?>
Now it will print the current date and time of the selected timezone.


Full Source Code
<?php
extract($_POST);
date_default_timezone_set("$timezone");
echo "Time details";
echo "<pre>";
print_r( getdate() );
echo "<pre>";
echo "Current Time : ";
echo date("H:i:s");
echo "<br>";
echo "Current Time Zone name : ";
echo $timezone;
?>
<form method="post">
<select id="timezone" name="timezone">
<?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
foreach( $timezone_identifiers as $value ){
if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $value ) ){
$ex=explode("/",$value);//obtain continent,city
if ($continent!=$ex[0]){
if ($continent!="") echo '</optgroup>';
echo '<optgroup label="'.$ex[0].'">';
}

$city=$ex[1];
$continent=$ex[0];
if($value == $timezone)
$selected = 'selected';
echo '<option '.$selected.' value="'.$value.'">'.$city.'</option>';
$selected = '';
}
}
?>
</optgroup>
</select>
<input type="submit">
</form>

Saturday, March 5, 2011

How to execute PHP code in html page

When we access a webpage the server decides how to pass the page information to the client. If the page is an html page (.html) the server sends the data direct to the client. But if the page is a server script page ( eg : .php ) the server process the page and send the output to the user.

If we have an html page and we would like to embed some PHP code in that page, usually its not possible by changing the file extension. But using .htaccess file we can make it possible without changing the file extension. Create a .htaccess file and add the following code.
AddType application/x-httpd-php .html
Upload this file into the root folder.

Now the server processes the .html page as .php file.

Example html code

Page name: sample.html
<html>
<head><title>Run PHP from html page</title></head>
<body>
<?php echo "this is from index.html"; ?>
</body>
</html>

Monday, February 21, 2011

Create a contact form in Facebook page using php,Ajax and FBML

A Facebook page is a public profile page about our business to share with Facebook users. Any Facebook user can create fan pages, if he has a number of 25 fans. Mainly the Facebook profile page is description about our self or our product. If we add a contact form in these page users can easily contact us. The following example shows how to create an AJAX based contact form in the Facebook page.

To create a page, go to applications and add FBML application. This application will add a box in our webpage and here we can add HTML or FBML (Facebook Markup Language) for enhanced Page customization.

Step 1 :Create a Contact form in page
Create a contact form in the page to get the data’s from the user. We can use our simple html to create the form.

<form method="post" action="http://www.domain-name.com/contact-facebook.php">
<p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</p>
<p>
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
</p>
<input type="button" value="Submit">
</form>
The above is a simple contact form. We are submitting the form data’s using ajax. So to invoke an ajax function, we must call the ajax function in a particular event. We are trying to call the ajax function in the onclick event. So we can change the button code as follows.

<input type="button" onclick="return sendFormData();" value="Submit">
Step 2 : Create the ajax function

Facebook doesn’t allow us to use any JavaScript we like to use. They have created a JavaScript library to access the DOM, ajax, events etc. This is known as FBJS. We are using these functions to work with the forms. Our ajax function is as follows.


<script><!--
function sendFormData()
{
// creating a new FBJS AJAX object
var ajax = new Ajax();
ajax.responseType = Ajax.FBML;

// creating a handle to get response from the server
ajax.ondone = function(data)
{
document.getElementById('name').setValue('');
document.getElementById('email').setValue('');
new Dialog().showMessage('Confirmation', data);
}
// get the form values
var fields = { 'name' : document.getElementById('name').getValue(), 'email' : document.getElementById('email').getValue() };
ajax.post('http://www.domain-name.com/contact-facebook.php', fields);
return false;
}
//--></script>

Working
First the above function creates an Ajax object using FBJS class. After that we create a response type to FBML

Define a call back function to handle the response from the server. After execution of the requested server page this function executes. Here we have removed the textbox contents and create a Facebook alert box to popup the result message from the server. We can use various types of dialog boxes here.

Getting the form elements values and keep these values in an array. We are using FBJS getValue function to get the element values.

Using the ajax.post function we are sending this data to our server file. The server file processes the data’s.

return false is used to prevent the script from page submission.

Step 3 : Create the mail sending code

Create a mail sending code and name it as 'contact-facebook.php'. Keep the file in the root folder of our server. Add a main sending code as follows.
<?php
extract($_POST);
// create a mail sending code
$to = 'sample@sample.com';
$subject = ' Contact message from Facebook Client';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$name.' <'.$email.'>' . "\r\n";

$message = '<table width="458" border="0"><tr><td width="120">Name : </td><td width="328">'.$name.'</td></tr><tr><td>Email : </td><td>'.$Email.'</td></tr></table>';

if (mail($to, $subject, $message, $headers))
$answer = "Thank you for contacting us";
else
$answer = "Error.. Cannot send the mail";
// mail sending code ends
echo $answer;

?>

The above code sends the mail to the mail id we specify. Also will populate the result message in the Facebook page.


FBML Source Code

<script><!--
function sendFormData()
{
// creating a new FBJS AJAX object
var ajax = new Ajax();
ajax.responseType = Ajax.FBML;

// creating a handle to get response from the server
ajax.ondone = function(data)
{
document.getElementById('name').setValue('');
document.getElementById('email').setValue('');
new Dialog().showMessage('Confirmation', data);
}
// get the form values
var fields = { 'name' : document.getElementById('name').getValue(), 'email' : document.getElementById('email').getValue() };
ajax.post('http://www.domain-name.com/contact-facebook.php', fields);
return false;
}
//--></script>



<form method="post" action="http://www.domain-name.com/contact-facebook.php">
<p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</p>
<p>
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
</p>
<input type="button" onclick="return sendFormData();" value="Submit">
<p id="ajaxMessage"></p>
</form>

Friday, February 4, 2011

how to disable mouse over of a youtube video ?

If we are embedding youtube videos in our webpage, usually we can play/pause the videos. Even we will redirect to youtube video page. Normally we can’t change the properties of play/pause functionality on mouse over. But we can disable the area of the video by using css .

First embed the youtube video in our page.
<embed src="http://www.youtube.com/v/R55e-uHQna0&autoplay=1" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed>
After that create a div with absolute position similar as the height and width of the video.
Set a transparent background for that div.

<style type="text/css">
#apDiv1 {
position:absolute;
width:425px;
height:350px;
background:url(transparent.png);}
</style>
<div id="apDiv1"></div>

So no event will work on the flash video file. This will be applicable for all flash videos.

Source Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Disable mouse over of a youtube video</title>
<style type="text/css">
#apDiv1 {
position:absolute;
width:425px;
height:350px;
background:url(transparent.png);}
</style>
</head>
<body>
<div id="apDiv1"></div>
<embed src="http://www.youtube.com/v/R55e-uHQna0&autoplay=1" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed>
</body>
</html>

Thursday, February 3, 2011

Hidden form field to prevent spam

Most of the website has a contact form to send emails to webmasters. And most of these forms are targeted by spam bots. They automatically fill the data’s in the form elements and submit these data’s and as a result our mail box will full of spam emails.

In order to avoid this spam emails we can use Captcha . A Captcha is an image that contains a verification code. It may be a text or a number, or a combination of both
The user must enter the verification code to prove that the entry is not a spam. We are checking the verification code in the server side. But now a day’s spam bots have the ability of character recognition and probably they can break the Captcha. So we need to increase the complexity of Captcha verification code. But it will very difficult for users to read the verification code.

Hidden Form Field

This is one simple way to prevent the spam data’s. This is also knows as Invisible Captcha. Just add an extra hidden field in the form. Using css hide the visibility of the text box. Noramlly humans can't see the hidden form elements and they wont fill the datas. So the this field remains empty.But spam bots are fill all form elements. So in the server side we can check the hidden filed value , and can check whether it’s a spam or not.

Example :

<label for="email">Email:</label><input type="text" name="txtemail" value="" />
<input class="confirmation-field" type="text" name="txtCaptcha" value="" />
<style>
.confirmation-field { display: none; }
</style>

Monday, January 17, 2011

How to embed YouTube Videos as Valid XHTML 1.0 ?

Youtube embed code help us to embed the youtube videos in our webapge. The youtube embed code is similar as follows.
<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/me0zQaMqhPY?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/me0zQaMqhPY?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>
If we embed the youtube embed code in our html page, normally we fails in the w3c validation. If we validate this page we can see that the error is because of the <embed> tag. The <embed> tag inserts a non-standard object or external content (typically non-HTML) into the document.

To remove the errors from the webapge we can remove the <embed> tag. The code is similar as follows.
<object type="application/x-shockwave-flash" width="640" height="385" data="http://www.youtube.com/v/me0zQaMqhPY"><param name="movie" value="http://www.youtube.com/v/me0zQaMqhPY"></object>
This will remove the w3 error message.
We can add the wmode by adding the following code
<param name="wmode" value="transparent">

You can set the autoplay feature by adding the autoplay parameter in the url.
&autoplay=1
like as follows
data="http://www.youtube.com/v/me0zQaMqhPY&autoplay=1"

Tuesday, January 11, 2011

Pagination in wordpress

If we have a large number of posts in wordpress , its not good to list all posts in a single page. So we need to restrict the listing of the posts. The query_posts() returns posts from the database . The main disadvantages of query_posts() is the lack of pagination .We can use parameters to change the listing of posts. Suppose we have a number of 50 posts in our site, it’s better to use pagination in the site. Here am trying to explain about how to use pagination in wordpress with query_posts().

First we need to install a plugin for pagination. We can use WP-Paginate plugin for pagination. We can download the plugin from the following link http://wordpress.org/extend/plugins/wp-paginate/ and install the plugin.

Add the following code in the page where you want to set pagination links.

<div class="navigation_nav">
<?php if(function_exists('wp_paginate')) {
wp_paginate();
} ?></div>

The above code will generate pagination navigation in the post page.

Next is to set the parameters for the query_posts(). We need to get the current page number and the pagination page number.

Add the following code before query_posts() to get the page number.
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
The above code get the page number from the GET variables. If the variable is not set , the page number is set to 1;

Next we need to pass the parameters to query_posts(). Use the following code to pass the parameters to query_posts().
query_posts("&paged=".$paged)
This will display a pagination link in the post page. We can set the number of posts to display by setting the 'posts_per_page' variable.
Similar as follows
query_posts("&paged=".$paged."&posts_per_page=10")
Also we can set the property in the admin side.

To set the post per page using admin panel
Go to Settings -> Select Reading -> edit 'Blog pages show at most' to your number.
But priority for post per page will be with the code that we added in the page.

Full source code:

After applying the codes the page will be similar as follows.


<?php
// get the page number and get the posts
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$q = "paged=".$paged.'&posts_per_page=2';
query_posts($q);
?>

<div class="navigation_nav">
<?php
// pagination links
if(function_exists('wp_paginate')) {
wp_paginate();
} ?></div>

<?php
// listing of posts
if (have_posts()) :
while (have_posts()) : the_post();
$custom_fields = get_post_custom(get_the_ID());
?>

Tuesday, January 4, 2011

Static DIV in a webpage

For an html object, there are five position properties: static, relative, absolute, fixed and inherit.
We can use fixed property to set a DIV fixed in a webpage and stays in the same place while scrolling.
The IE6 does not support position: fixed and shows it in the position following this text where it has been coded and it will scroll.

A position: fixed div needs to be positioned with regard to the intended viewport size. A div with position: fixed; top: 700px will never show on a screen resolution of 800 x 600 and scrolling will not make it appear.

The code is
<div id="static1">static DIV</div>
The styles are:-
#static1 { position: fixed; top: 95px; left: 30px; width: 220px; height: 40px; background-color:#00CCFF; }
Full Code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Static DIV</title>
<style>
#static1 {
background-color:#00CCFF;
height:40px;
right:5px;
position:fixed;
bottom:5px;
width:220px;
}
</style>
</head>
<body>
<div id="static1">Static DIV</div>
<div style="height:1000px;">
page contents
</div>
</body>
</html>