Thursday, March 26, 2009

Pagination in PHP

Pagination in PHP




Step One

  1. Connect to MySQL database.
For those who are new to PHP & MySQL and do not know how to establish connection with MySQL, may use the following config.php.file code.

//Host name

$host='localhost';

//User name

$user='root';

//Password

$pass='';

//Database name

$db='mydb';

//Establishing database connection

mysql_connect($host,$user,$pass);

//Select database

mysql_select_db($db) or die ("Database Connection Failed") ;

?>


Step Two
  1. Set Variables:
  2. Set table name you want to use (Table must contain an auto increment field named “Id”).
  3. Set the column name you want to show.
  4. Set number of rows per page (default is 5 rows/page).
After configure variables as defined above, simply run the script and enjoy {:-Þ

//Include config file

includes('config.php');

//Table name

$myTable='Mytable';

//Column Name

$columnName='Columnname';

//How many rows to show per pg

$rowsperpg=5;

//by default we show first pg

$pgnum=1;

//if $_GET['page'] defined, use it as first page number

if(isset($_GET['page']))

{

$pgnum=$_GET['page'];

}

//counting the offset

$offset=($pgnum-1)*$rowsperpg;

$test="SELECT * FROM '".$myTable."' LIMIT $offset,$rowsperpg";

$run=mysql_query($test) or die('selection fail');

//print

$count=mysql_num_rows($run);

if($count > 0)

{

while($res=mysql_fetch_assoc($run))

{

echo '

';

echo '

';

echo '

Event: '.$res[$columnName].'
';

echo '
'
;

}

//how many rows we have in db

$query="SELECT COUNT(Id) as numrows FROM '".$myTable."' ";

$res=mysql_query($query) or die('Error Query failed');

$row=mysql_fetch_assoc($res);

$numrows=$row['numrows'];

//how many pg we have when using paging?

$maxpg=ceil($numrows/$rowsperpg);

// print the link

$self=$_SERVER['PHP_SELF'];

$nav='';

for($page=1;$page<=$maxpg;$page++)

{

if($page==$pgnum)

{

$nav.="$page";

}

else

{

$nav.="$self?page=$page\">$page";

}

}

if($pgnum>1)

{

$page=$pgnum-1;

$prev="$self?page=$page\">[Prev]";

$first="$self?page=1\">[First Page]";

}

else

{

$prev=' ';

$first=' ';

}

if($pgnum<$maxpg)

{

$page=$pgnum+1;

$next="$self?page=$page\">[Next]";

$last="$self?page=$maxpg\">[Last Page]";

}

else

{

$next=' ';

$last=' ';

}

echo '

'.$first.' '.$prev.' '.'page'. $pgnum.' '.' of'.' '.$maxpg.' '.$next.' '.$last.'
';

}

if($count <= 0)

{

?>

<div style="color: #FF3300" align="center">

<p><h5>No Record Availableh5>p>

div>

}

?>

Wednesday, March 25, 2009

Google Docs Security Problem Solved

I am a fan of Google Docs(beta). When I was trying to find out templates on Google Docs, I felt that I got the private spreadsheet of someone. I searched for this issue on the internet but did not find a satisfied answer. Yesterday, I found the following link. Google had admitted this security problem but I think the problem has been solved.


http://www.pcworld.com/article/160927/google_docs_glitch_exposes_private_files.html

on Wikipedia

http://en.wikipedia.org/wiki/Google_docs#Data_safety_and_privacy

Friday, March 20, 2009

Search Your Network Game Using PHP

Search games on your network, simply using PHP. This script uses a cool module of PEAR, Net_GameServerQuery- a common API to query Half Life server. PEAR () is a framework and distribution system for reusable PHP components. You need to install PEAR module Net_GameServerQuery on your PHP installation.
First change configuration to match your game server. Set IP address ( $ip ) and game type ( $protocol ) variables.



Note: Click on image for clear view.

Thursday, March 19, 2009

JAVA connection with MySQL using JDBC in Eclipse

We will discuss JAVA-MySQL connection using JDBC (Java Database Connectivity)

JDBC:

JDBC is a standard API that allows JAVA programs to access databases. The JDBC API is a collection of interfaces and classes written in the JAVA Programming Language. We can write applications that connect to databases, send SQL queries, and get the results using these standard interfaces and classes.

A JDBC driver implements these interfaces and classes for a particular Database Management System. A Java Code loads the specified driver for a particular DBMS before it establish a connection with a database.


Download JDBC Driver:


First of all you have to download JDBC driver (usually named mysql-connector-java-version).
For Example: http://ftp.fju.edu.tw/Database/MySQL/Downloads/Connector-J/

Extract downloaded zip file and copy extracted folder to your plugins folder in Eclipse Directory.
For Example: C:\Eclipse\plugins\mysql-connector-java-version


Import JDBC Driver in Eclipse.


1. Right Click on your Project in Eclipse -> Select Properties.
2. Select Java Build Path->selcect Libraries tab->press Add External JARs button.
3. Select mysql-connector-java-version-bin file from downloaded mysql-connector-java-version folder.

Done. Now you are ready to establish JAVA-MySQL connection.


JAVA Code Example:

For Example we have a database named “riksof” with a table employees(id,name,email,designation) where “id” is primary key and auto_increment.



/*Define a connection url*/
String host = "localhost";
String db = "riksof";
String tb = "employees";
String db_user = "dbuser";
String db_pw = "dbpassword";

String db_url = "jdbc:mysql://"+host+":3306/"+db+"?user="+db_user+"&password="+db_pw;

Connection conn = null;
Statement stmt = null;
String query = "";
ResultSet result = null;
PreparedStatement ps = null;



/* Load driver and Establish a connection */
try{
conn = DriverManager.getConnection (db_url , db_user , db_pw);
stmt = conn.createStatement();
}catch(Exception connectionExp){
System.out.println("SQL Connection not Established: " + connectionExp.getMessage());
}

try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}catch(Exception driverExp){
System.out.println("Driver not Found : " + driverExp.getMessage());
}



/* Now Display all records */
query = "SELECT * FROM " + tb;
try{
result = stmt.executeQuery(query);

while(result.next()){
System.out.println(result.getString("id"));
System.out.println(result.getString("name"));
System.out.println(result.getString("email"));
System.out.println(result.getString("designation"));
System.out.println("-------------------------------");
}
}
catch(Exception sqlExp){
System.out.println("SQL Exception: " + sqlExp);
}



/*Insert a single record*/
query = "INSERT INTO employees(name,email,designation) VALUES('Name','Email','Designation')";

try{
conn.createStatement().executeUpdate(query);
System.out.println("Record Stored.");
}
catch (SQLException insertExp) {
System.out.println("SQLException Caught: " + insertExp.getMessage());
}

Google Special Syntaxes

In the era when people go online before the morning tea, Google search engine is an essential part in our everyday life.
Being a full-text search engine Google indexed entire website instead of title, links and description. Google search engine support Boolean operators, basic AND, OR, and quoted strings, as well as it offers special syntax for quick and precise query. Here are some of the common syntax which are very useful for professional peoples;

intitle:
intitle: search is restricted to page titles
intitle:"pakistan"
allintitle:"kashmir dispute" pakistan

inurl:
inurl: search is restricted to URLs.
inurl:view.shtml
allinurl:search help

intext:
intext: searches only body text
intext:"riksof.com"

inanchor:
inanchor: searches for text in a page's link anchors.
inanchor:"university"

site:
site: search by either a web site or a top-level domain.
site:gov
site:pk
site:edu.pk

link:
link: gives a list of pages linking to the particular URL.
link:www.riksof.com

cache:
cache: find copy from Goolge indexed cache even it is no longer available at its original location.
cache:www.amazon.com

daterange:
daterange: limits your search to a particular date or range of dates that a page was
indexed.
Note that daterange: works with Julian, not Gregorian dates (the
calendar we use every day).
"Osama Bin Laden" daterange:2452389-2452389
Aerospace daterange:2452389-2452389

filetype:
filetype: searches the suffixes or file extensions.
java filetype:pdf
"marketing" filetype:ppt

related:
related: finds pages that are related to the specified page.
related:www.ebay.com
related:www.cricinfo.com

info:
info: provides a page of links to more information about a specified URL.
info:www.wikipedia.com

phonebook: //not very useful for Pakistan
phonebook: phone number looks up.
phonebook: Karachi

There are still more syntax for easy, precise and rapid search and Google is adding more day by day.

Wednesday, March 18, 2009

PHP Image Gallery & Truncate a string in Smarty

PHP Image Gallery
Description:

This is an image gallery script that allows you to simply upload new full sized images in FTP and the script will automatically create the thumbnails for those images and add those images to a paged thumbnail gallery suitable for browsing.

Instructions:
First of you have to set the variables in the code below.
  1. Scroll down to about line 30 and look for $config['size']. Set this to the maximum width or height you want your image thumbnail to be.
  2. On the next line in the $config['imagequality'] set this to the JPEG quality you would like your thumbnails to be. I recommend you keep it set to 70.
  3. $config['rows'] and $config['cols'] are the number of rows and number of columns of thumbnail images you want shown on each page.
  4. $config['maxShow'] is the number of page numbers to show at one time. for instance if you have 100 pages of images, you can set this to only show the page numbers of the 10 pages close to where you currently are.
  5. $config['thumbs'] is the relative path to where you want the thumbnail images to be stored. Include the trailing slash.

File Permissions:

  1. You'll need to change the permission on the directory you set $config['thumbs'] to. CHMOD it to 775 or 777 so PHP and GD2 can automatically write and create your thumbnails in that directory.

Changing the Look:

  1. The entire gallery table is controlled by the CSS settings you'll find toward the bottom of the gallery.php file. I tried to comment each specific part of the CSS and what it controls so you can easily change the look of the gallery without actually having to actually edit any of the PHP.

Here is the Code:

You can download the gallery.php file from the following link.

http://www.ricocheting.com/scripts/gallery.html

Truncate a string in Smarty

Suppose you have a sentense in smarty that contains more characters and the rows of the table where you wants to show it will become wrap which sounds very bad. So you can use smarty variable modifier called 'truncate'.

How to use Truncate:

It has following syntaxes,
truncate:how_many_characters_to_show:what_characters_appear_at_end
truncate:int:int
lets,
$yourString = "Hello World";
  1. {$yourString|truncate}//output// Hello World
  2. {$articleTitle|truncate:3}//output// Hel...
  3. {$articleTitle|truncate:3:""}//output// Hel
  4. {$articleTitle|truncate:3:"---"}//output// Hel---
You can also find more detail from
http://www.smarty.net/manual/en/language.modifier.truncate.php
Special Thanks:
Ihsanuilah Khan

Pentaho



Pentaho BI project is an open source project. It is used for many purpose.

  • Reporting
  • Analysis
  • Dashboard
  • Data Mining
  • Work flow
Pentaho BI have two versions, one is community and other is enterprises edition.we will use in our recent project of COI(HCCS) for data reporting.Basically it consist of a server BI and client side design studio.It uses tomcat as web server.If some one to use it first start the BI server with sh command from terminal and tomcat also from sh command.It also have a plugin structure.Design studio can also be installed in eclipse as plugin.




Friday, March 13, 2009

LDAP integration to change password

Once you have installed and configured LDAP on your Linux server you will probably need to change user’s passwords in future. For this you can allow user to login and change their password from shell.
User management from shell is not a sufficient way, you might be interested to find a way to change password without allowing user to log into server. And in case if you has particular login registration framework, then you would like to integrate LDAP with it.
I choose PHP to perform the task.
First thing, allow user to change password in slapd.conf file;

access to attr=userPassword
by self write
by anonymous auth
by * none

The next step is ldap bind with user credentials for authentication;

if(isset($username) and isset($newpassword) and isset($oldpassword)) {
$ldapconn = ldap_connect("hostname", 389);
$ldapbind=@ldap_bind($ldapconn,"uid=".$username.",dc=example,dc=com",$oldpassword);
if($ldapbind){

//If user gives correct username and password, then;

if( ldap_mod_replace ($ldapconn, "uid=".$username.",dc=host,dc=com",
array('userpassword' => "{MD5}".base64_encode(pack("H*",md5($newpassword)) ){
print "Password changed successfully ";
}else{
print "Failed to change password";
}
}

Thursday, March 12, 2009

Secure our Joomla webs from Hackers


As we know that 'Joomla' is really amazing open source product for web development but as far as security is concern like others we may not rely on 'Joomla'.

Some days ago a website of someone was hacked that was built using 'Joomla' but thanks to allmighty Allah that issue have resolved. This is one case that I know but may be many organization have faced or facing such type of problems. So I thought to search about this problem and finally I found some blueprints from www.joomlasecurity.info/ this web is also by 'Joomla' for their clients who use 'Joomla'. Although in this site they define each and every issue that concerns with security of 'Joomla' and other webs but the key points are mentioned as below.

I hope it will be helpful for developers specially who are using 'Joomla' for developing their webs.

  1. Use the latest version of Joomla.
  2. Use only secure third party plugins and also keep them updated.
  3. Use secure username and password for administrators.
  4. Use an SEF (Search Engine Friendly) component that makes your Joomla more secure.
  5. Use a secure web host / secure server configuration.
  6. Don’t tell everyone about your configuration.
  7. Write-protect your Joomla configuration file (make unwriteable).
  8. Delete Joomla templates that you do not use.

Wednesday, March 11, 2009

Joomla Template

Joomla look and feel can be changed due to its framework. Joomla template can be changed from administrator side.I want to explain basic requirements to design a joomla template.
templateDetails.xml
This file define information about template.D should be in uppercase(This is standard file format).An XML format metadata(data about data) file that tells Joomla! what other files are needed when loading a web page that uses this template. It also tells the author, copyright and what files make up the template (including any images used). The last use of this file is for installing a template when using the admin backend.

Monday, March 9, 2009

Automatic login script

This script is to automated our log-in to some site.
You must have cURL installed to use this script.
When I started to code this script , at that time I was having some difficulties to code and finally I got the success to programmed auto log-in script. From internet I have research allot to create such a script , but there is no correct solution available for this script on internet . This script is really help you to logging in to different site automatically when you run it .

// INIT CURL
$ch = curl_init();

// SET URL FOR THE POST FORM LOGIN
curl_setopt($ch, CURLOPT_URL, 'http://www.external-site.com/Members/Login.php');

//Reference URL that where you going to login
curl_setopt($ch, CURLOPT_REFERER, "RefUrl");

// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);

// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'fieldname1=fieldvalue1&fieldname2=fieldvalue2,...');

//Cookie file
curl_setopt ($ch, CURLOPT_COOKIEFILE, 'cookie.txt');

// IMITATE CLASSIC BROWSER'S BEHAVIOUR : HANDLE COOKIES
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

//set session cookie
curl_setopt ($ch, CURLOPT_COOKIE, 'cookie.txt');

//Usage of CURLOPT_FOLLOWLOCATION is important when sites use URL redirectors for //file downloads
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);


// Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
// not to print out the results of its query.
//Instead, it will return the results as a string return value
// from curl_exec() instead of the usual true/false.
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

// EXECUTE 1st REQUEST (FORM LOGIN)
$result = curl_exec($ch);

// CLOSE CURL
curl_close ($ch);

Monday, March 2, 2009

Ldap authentication with Openbravo

The following instructions allow use of an Ldap server to authenticate users to OpenBravo ERP. I first unsuccessfully attempted to use a custom authentication manager to implement LDAP support. If you have been able to do it, I would be very keen to know how it was done.

  1. Copy this file to /AppsOpenbravo/src/com/riksof/authentication/LdapLoginHandler.java
  2. Please modify objectDN string to correspond to your setup.
  3. Login to postgres with the database user created at installation time: psql - U tad -d openbravo
  4. Insert the following entry:
    insert into ad_model_object(ad_model_object_id, ad_client_id, ad_org_id, isactive, action, classname, isdefault, created, createdby, updated, updatedby) values (1006100001, 0, 0, 'Y', 'X','com.riksof.authentication.LdapLoginHandler', 'Y', current_timestamp, 100, current_timestamp, 100);
  5. Also update entry to use our login class:
    update ad_model_object_mapping set ad_model_object_id=1006100001 where mappingname='/secureApp/LoginHandler.html';
  6. Compile and deploy OpenBravo to use Ldap.