Category Archives: php

PHP Posts

Speed up your PHP website, a consultant’s guide

Yesterday a friend was requesting a MYSQL/PHP Consultant to speed up his websites, and today I was reading few comments and solutions on his facebook : Use APC, mem_cache for PHP, mysql query caching, use nginx instead of Apache, Use mysqli extension instead of adodb or mysql extension … etc. Of course all of these could be solutions, but unless you have previously located what the problem really is.A website could be slow for many reasons, and to be able to fix it and make it run faster you have to first find problem. What you will need to know is :

1- Understand the business :

Before looking into PHP or MySQL, have a first look at the website(s) and answer these two questions :

– What is slow
– Why is it slow

Look at the page size, images, video, flash, … your issue might be in the client side and everything else might be good.
Use a tool like Firefox web developer extension and disable everything : CSS, Javascript, Images… and load the page as html to feel the difference.
The business here is NOT the business logic behind the website, it’s the interface that people use to interact with the website. If everything looks okay, you can go for further server-side investigations.

2- Understand the production environment : Operating system, PHP and MySQL versions, PHP extensions running, PHP and MySQL configurations.

Do not start optimizing code or database unless you know the exact problem, otherwise you have to start by understanding and optimizing the working environment. Some tweaks in PHP and MySQL settings might fix your problem and you won’t probably need to dig deeply into any code.

3- Understand the code :

If the websites you are looking to optimize are using a common framework or CMS, let’s say Drupal, WordPress, Zend Framework, Symfony… such websites you can deal with separetely since most optimization issues should be known and you will easily find your way to speed things up.

Otherwise, for custom code and custom application development, start with debugging and focus firstly on the database. That’s where most slow issues come from, especially if the concerned website was running fast in the beginning then become slow over the time due to database size going bigger, query & index issues…

4- Debug : detect and locate bottlenecks

Debuggers are your friends here, whatever the environment you are running. Answer again previous questions (What and Why) but this time with relation to the code itself.

You might consider running a stress test here to simulate real working environment. Such tests could help you understand more networking issues and make it easier to locate slowliness based on real scenarios. Test should also simulate real environment, and you will need to save speed result for comparison later.

5- Solution proposal and action plan

Now you can go ahead and set possible solutions : fixing bugs, caching code/queries, tweak your settings… Make sure your modifications will not affect other working website in the same environment – if any is somehow related or linked.

Finally you can run previous stress test with new configuration and updates to see the difference in speed gained. A report of previously mentioned steps should be written including result.

Leave a comment

Filed under php

Know About Elgg

Elgg is an award-winning open source social networking engine that provides a robust framework on which to build all kinds of social environments, from a campus wide social network for your university, school or college or an internal collaborative platform for your organization through to a brand-building communications tool for your company and its clients. If you are looking to create your own social application, want to build and run a site for your organization, or introduce a social layer into your technology stack, Elgg is a great choice.

Elgg highlighted features :

Powerful Data Model: Elgg provides a powerful data model making the creation of different entities simple, yet flexible.
Activity Streams: The granular activity stream API ensures your plugins can push the required content to your users.
Plugin API: Use Elgg’s powerful plugin API to build and add your required features.
User Management: Elgg handles your user management and relationship requirements.
Access controls: All objects in Elgg can have an access control level applied making granular access permissions possible.
Web Services API: Expose functionality through the REST API by building a plugin and then either publish the API for other developers to build clients or provide your own.

Tons of plugins available in gallery to extend Elgg functionalities. Elgg run on a LAMP stack and require MySQL 5+, PHP5.2+ installed as Apache module. Released under the GPLv2.

Leave a comment

Filed under php

Array Functions in PHP with Example

<?php

$x=1;
switch($x)
{
case 1://sample use of array
$arr=array(“fname”=>”vijay”,”lname”=>”baskar”);
print_r($arr);
echo “<br>”;
echo $arr[‘lname’];
echo “<br>”;
print_r(array_change_key_case($arr,CASE_UPPER));//to change key case
echo “<br>”;
print_r(array_chunk($arr, 1,true));
break;
case 2://combining two arrays make any one as key and another as values
$arr1=array(“a”,”b”);
$arr2=array(“1″,”2”);
print_r($arr2);
echo “<br>”;
print_r(array_combine($arr1, $arr2));
break;
case 3://count array values and make count as values and original values as keys
$arr1=array(“a”,”b”,”a”);
print_r(array_count_values($arr1));
break;
case 4:
$arr1=array(“a”,”b”,”a”);
$arr2=array(“1″=>”d”,”b”,”a”);
print_r(array_diff($arr1, $arr2));
echo “<br>”;
print_r(array_diff_assoc($arr1, $arr2));
echo “<br>”;
print_r(array_diff_key($arr1, $arr2));
echo “<br>”;
//print_r($arr2);
break;
case 5:
function fun($a,$b)
{
if($a===$b)
{
echo “hi”;
}
else
{
echo “hello”;
echo “<br>”;
}
}
$arr1=array(“a”,”b”,”a”);
$arr2=array(“d”,”b”,”a”);
print_r($arr1);
echo “<br>”;
print_r($arr2);
echo “<br>”;
print_r(array_diff_uassoc($arr1, $arr2,”fun”));
break;
case 6://fills the array with the value what we give
$a=(array_fill(2,3,’v’));
print_r($a);
break;
case 7:
function fun($a)
{
if($a===”1″)
{
return true;
}
}
$arr=array(“1″,”2″);
print_r(array_filter($arr,”fun”));
break;
case 8:
$arr=array(“1″,”2”);
print_r(array_flip($arr));
break;
case 9:
$arr=array(“1″,”2”);
$arr1=array(“2″,”23”);
$arr2=array(“2″,”4”);
print_r(array_intersect($arr, $arr1,$arr2));
echo “<br>”;
echo array_key_exists(“1”, $arr);
echo “<br>”;
print_r( array_keys($arr));
break;
case 10:
$arr=array(“1″,”2”);
$arr1=array(“1″,”1”);
function fun($a,$b)
{
if($a===$b)
{
return “hi”;
}
return “hello”;
}
print_r(array_map(‘fun’,$arr,$arr1));
break;
case 11:
$arr=array(“a”=>”1″,”b”=>”2”);
$arr1=array(“a”=>”4″,”c”=>”3”);
print_r($arr);
echo “<br>”;
print_r($arr1);
echo “<br>”;
print_r(array_merge($arr,$arr1));
echo “<br>”;
print_r(array_merge_recursive($arr,$arr1));
break;
case 12:
$arr=array(“0″=>”4″,”1″=>”2″,”2″=>”4″,”3″=>”5”);
$arr1=array(“5″,”5″,”5″,”5”);
// print_r(array_multisort($arr));
//       print_r(array_pad($arr,6,’a’));
//        echo “<br>”;
//        print_r($arr);
//        echo “<br>”;
//       print_r(array_pop($arr1));
//          echo “<br>”;
//          print_r($arr1);
//          echo “<br>”;
//        print_r(array_product($arr1));/
//        echo “<br>”;
//        print_r(array_push($arr1,10,10));
//       echo “<br>”;
//       print_r($arr1);
//array_push
//print_r(array_ra($arr1,1));
print_r(array_replace($arr1, $arr));
//print_r($f);
print_r($arr1);
// array_s */
break;
case 13://again doubt
$a=array(“a”=>”zero”,”b”=>”one”);
$a1=array(“a”=>”zero”,”b”=>”one”);
print_r($a);
echo “<br>”;
print_r($a1);
echo “<br>”;
function fun1($c,$c1)
{
if($c==$c1)
{
echo “Key is not Equal:”.$c.” and “.$c1;
echo “<br>”;
}
}
array_diff_uassoc($a, $a1,”fun1″);
//print_r(array_diff_uassoc($a, $a1,”fun1″));
break;

case 14://multisort in array

$a=array(“a”=>”5”,”b”=>array(“2″,”8″),”c”=>”10”);
$a1=array(“a”=>”5″,”b”=>”one”,”c”=>”5″);
array_multisort($a1,SORT_DESC,$a);
print_r($a1);
print_r($a);
break;
case 15:
$a=array(“a”=>”5″,”b”=>”1″,”c”=>”3″,”d”=>”5”);
$a1=array(“15″,”20”);
function fun2($f,$f1)
{
echo “hi”;
return $f;
echo $f1;
}
print_r(array_reduce($a,’fun2′,4)) ;
echo “<br>”;
print_r(array_reverse($a,false));
echo “<br>”;
print_r(array_reverse($a1,true));
echo “<br>”;
print_r(array_search(1,$a));
echo “<br>”;
print_r(array_shift($a1));
echo “<br>”;
print_r($a1);
echo “<br>”;
print_r(array_slice($a,-4,2));
echo “<br>”;
break;
case 16://to delete and replace
$a=array(“a”=>”5″,”b”=>”1″,”c”=>”3″,”d”=>”5”);
$a1=array(‘v’);
print_r(array_splice($a,4,0,$a1));
print_r($a);
print_r(array_unique($a));
break;
case 17:
$a=array(“a”=>”s”,”b”=>”s”,”c”=>”s3″,”d”=>’s3′);
print_r(array_sum($a));
break;
case 18:
function myfunction($v1,$v2)
{
if ($v1===$v2)
{
echo “equal”;
echo $v1;
echo $v2;
echo “<br>”;

}
else
{
echo “not equal”;
echo $v1;
echo $v2;
echo “<br>”;
}

}
$a1=array(“a”=>”Cat”,”b”=>”Dog”,”c”=>”Horse”);
$a2=array(1=>”Cat”,2=>”Dog”,3=>”Fish”);
print_r(array_udiff($a1,$a2,”myfunction”));
break;

case 19:
$a=array(1,2);
print_r(array_unshift($a,5,4,4));
print_r($a);
break;
case 20:
$a=array(1,2);
$a1=array(1,$a,2);
arsort($a);
//print_r($a1);
// print_r(array_slice($a1,2,1));
print_r($a);
//            function func(&$a,$b)
//            {
//                $a=9;
//                echo $a . $b;
//                echo “<br>”;
//            }
//            array_walk_recursive($a1,’func’);
//            print_r($a1);
break;
case 21://store variable and value in array
$a=’vijay’;
$b=’baskar’;
print_r(compact(‘a’,’b’));
//print_r($r);
break;
case 22:

$a1=array(3,4,4);
$a=array($a1,1,2,6);
//             print_r(count($a,1));
//             echo “<br>”;
echo current($a1);
echo “<br>”;
echo end($a1);
echo “<br>”;
print_r(each($a1));
break;
case 23:
$c=1;
$a1=array(“a”=>3,”b”=>4,”c”=>4);
//             extract($a1,EXTR_PREFIX_SAME,’dup’);
//             echo “\$a=$a ; \$b=$b; \$c=$c”;
//             echo $dup_c=$dup_c;
//echo next($a1);
echo prev($a1);
break;
case 24://giving ranges
$a=range(5,40,4);
print_r($a);
break;
}
?>

Leave a comment

Filed under php

PHP Data Object

 PHP Data Object is a Database Connection Abstraction Library for PHP 5.

PDO Introduction

  • a Lightweight DBMS connection abstract library (data access abstraction library)
  • PDO can use exceptions to handle errors, which means anything you do with PDO should be wrapped in a try/catch block.
  • PDO is a database access layer providing a uniform method of access to multiple databases.
  • PHP5 is written in compiled language like C & C++

PDO - db abstraction layer

Database Support

Activation PHP Data Objects Extension

To use PDO, check whether PDO extension exist or not. Try to open your php extension folder. For example, in my computer, the directory: app/php5/ext.

PDO library at PHP extension folder

Then, open your php.ini. Usually within c:/windows (depend on your php installation). Uncomment at line extension=php_pdo.dll, extension=php_pdo_mysql.dll. If still not exist, write them.

PDO library at PHP extension folder

Restart your apache. You can restart from services. If, you use windows XP, you can access from start > control panel > Performance and Maintenance > Administrative Tools > Services. Find apache, then click restart.

Restart apache

Now, we test to connect to database. We use mysql server. Before test, please create a database named “test”. Then create table “books” with query like this:

CREATE TABLE `books` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(150) NOT NULL,
  `author` varchar(150) NOT NULL,
  `description` varchar(255) NOT NULL,
  `on_sale` tinyint(1) NOT NULL,
  PRIMARY KEY  (`id`)
);

Following query for sample data:

INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (1, 'PHP AJAX', 'Andreas', 'This is good book for learning AJAX', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (2, 'PHP Eclipse ', 'George', 'Nice book', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (3, 'PHP Prado', 'Junyian', '-', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (4, 'PHP Zend Framework', 'Ozulian', 'great', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (5, 'PHP Web Services', 'Bobi', '', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (6, 'PHP API', 'Hugo', '', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (7, 'PHP SEO', 'Monteo', '', 1);

Now, this is sample connection to mysql database:


<?php
$host 	= "localhost";
$db	= "test";
$user	= "root";
$pass	= "admin";

$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);

$sql = "SELECT * FROM books";
$q	 = $conn->query($sql) or die("failed!");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
  echo $r['title'];
}

?>

Prepared Statement

PHP Extension for MySQL and SQLite don’t offer this functionality. Ok, I will show a sample. I believe, from that sample you will understand what is prepare statement.

A prepared statement is a precompiled SQL statement that can be executed multiple times by sending just the data to the server.

It has the added advantage of automatically making the data used in the placeholders safe from SQL injection attacks.

You use a prepared statement by including placeholders in your SQL.

<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

$title = 'PHP AJAX';

// query
$sql = "SELECT * FROM books WHERE title = ?";
$q = $conn->prepare($sql);
$q->execute(array($title));

$q->setFetchMode(PDO::FETCH_BOTH);

// fetch
while($r = $q->fetch()){
  print_r($r);
}

?>
in this simple example, query depends on a variabel (we write with ?).


$sql = "SELECT * FROM books WHERE title = ?";

Now, we manipulate this query to create the prepared statement and execute it:

$q = $conn->prepare($sql);
$q->execute(array($title))

Another sample:

$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
 

Positional and Named Placeholders

Positional Placeholders

$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));

The query above used question marks to designate the position of values in the prepared statement. These question marks are called positional placeholders.

We must take care of proper order of the elements in the array that we are passing to the PDOStatement::execute() method.

Named Placeholders

$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like :title AND author like :author ";
$q = $conn->prepare($sql);
$q->execute(array(':author'=>$author,
                  ':title'=>$title));

This use descriptive names preceded by a colon, instead of question marks. We don't care about position/order of value. That's why it called named placeholders.

 

Insert and Update Statement Use Prepared Statement

Example for Insert

<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// new data
$title = 'PHP Security';
$author = 'Jack Hijack';

// query
$sql = "INSERT INTO books (title,author) VALUES (:title,:author)";
$q = $conn->prepare($sql);
$q->execute(array(':author'=>$author,
                  ':title'=>$title));

?>

Example for Update

<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// new data
$title = 'PHP Pattern';
$author = 'Imanda';
$id = 3;
// query
$sql = "UPDATE books 
        SET title=?, author=?
		WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($title,$author,$id));

?>

Selecting Data

Fetch data into arrays or objects

  • PDO::FETCH_ASSOC: returns an array indexed by column name
  • PDO::FETCH_BOTH (default): returns an array indexed by both column name and number
  • PDO::FETCH_BOUND: Assigns the values of your columns to the variables set with the ->bindColumn() method
  • PDO::FETCH_CLASS: Assigns the values of your columns to properties of the named class. It will create the properties if matching properties do not exist
  • PDO::FETCH_INTO: Updates an existing instance of the named class
  • PDO::FETCH_LAZY: Combines PDO::FETCH_BOTH/PDO::FETCH_OBJ, creating the object variable names as they are used
  • PDO::FETCH_NUM: returns an array indexed by column number
  • PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names

I think this post most helpful one for your PDO !!!

All the best!!!


			

Leave a comment

Filed under php

Basic String Operation in PHP

Use this coding to understand basic string operation.

<?php
$x=1;
switch($x)
{
case 1:
echo “<h2>StripSlashes</h2>”;
$str=”Student’s listen here”;
echo “Using AddSlashes:<font color=blue>”.addslashes($str).”</font><br>”;
echo “Using StripSlashes:<font color=blue>”.stripslashes($str).”</font>”;
break;

case 2:
echo “<h2>StripCSlashes</h2>”;
$str=”Students listen here”;
echo “Using AddCSlashes:<font color=blue>”.addcslashes($str,’a..z’).”</font><br>”;
echo “Using StripCSlashes:<font color=blue>”.stripcslashes($str).”</font>”;
break;

case 3:
echo “<h2>Strnatcasecmp</h2>”;
echo strnatcasecmp(‘HELLP’,’hellp’).”<br>”;
break;
case 4:
echo “<h2>Strnatcmp</h2>”;
echo strnatcmp(‘HELLP’,’hellp’);
break;
case 5:
echo “<h2>Strip_tags</h2>”;
echo strip_tags(“<b><i>vijay</i></b>”,'<b>’);
break;
case 6:
echo “<h2>Strpbrk</h2>”;
echo strpbrk(‘hello da’, ‘ea’);
break;
case 7:
echo “<h2>Str_rot13</h2>”;
echo str_rot13(‘a’);
break;
case 8:
echo “<h2>Convert_Uuencode</h2>”;
$u= convert_uuencode(“abc”);
echo “Encoded: “.$u;
echo “<h2>Convert_Uudecode</h2>”;
echo “decode: “. convert_uudecode($u);
break;
case 9:
echo “<h2>Metaphone</h2>”;
echo metaphone(‘world’);
break;
case 10:
echo “<h2>Number_format</h2>”;
echo number_format(10000000,2,”,”,”.”);
break;
case 11:
echo “<h2>Parse_str</h2>”;
parse_str(‘a=10&v=name’,$arr);
print_r($arr);
break;
case 12:
echo “<h2>Sha1</h2>”;
echo sha1(‘vijay’);
$en= sha1_file(‘new.txt’,true);
file_put_contents(‘new.txt’, $en);
break;
case 13:
echo “<h2>bin2hex</h2>”;
$bn= bin2hex(‘vijay’);
echo $bn;
echo pack(‘H*’,$bn);
default:
echo “<h2>Give range b/w 1 to 13</h2>”;
}
?>

Leave a comment

Filed under php

Basic File Operations in PHP

Use this coding to understand basic file operation

<?php
$x=1;
switch($x)
{
case 1:
$file=’localhost/new.txt’;
//echo “<h2>Base name:</h2>”.basename($file);
echo “<h2>Base name:</h2>”.basename($file,’.txt’);
echo “<h2>Path information:</h2>”;
print_r(pathinfo($file));
//print_r(pathinfo($file),PATHINFO_FILENAME);
echo “<h2>Absolute Path:</h2>”.realpath(‘new.txt’);
echo “<h2>Directory Name:</h2>”.dirname($file);
break;

case 2://mode permissions

$file=’new.txt’;
chmod($file, 0700);
break;

case 3://clear cache
$f=’new.txt’;
$f1=fopen($f,’a+’);
echo “<h2>File size</h2>”.filesize($f);
ftruncate($f1,500);
//clearstatcache();
echo “<h2>File size</h2>”.filesize($f);
break;

case 4://copy file info to another
copy(‘new.txt’, ‘new1.txt’);
echo “<h2>data copied</h2>”;
break;
case 5:// To Know Disk spaces
echo “<h2>Total space in c directory:</h2>”. disk_total_space(‘c:’);
echo “<h2>Free space in c directory:</h2>”. disk_free_space(‘c:’);
break;
case 6://Match Function
echo “<h2>Using Match Function</h2>”;
$file=”new1.txt”;
if(fnmatch(‘new*’, $file))
{
echo “Pattern Matched”;
}
else
{
echo “Pattern Not Mached”;
}
break;
case 7://Pass thru function
echo “<h2>Pass Through Function</h2>”;

$file=fopen(‘new1.txt’,’r’);

fgets($file);
//rewind($file);//rewind goes beginning of file
echo fpassthru($file);
fclose($file);
echo “<h2>Read File</h2>”;
echo “<br>”;
echo readfile(‘new.txt’);
break;

case 8:
$file=’html.html’;
$f1=fopen($file,’r’);
echo fgetss($f1,100,'<b>’);
break;
case 9:
print_r(glob(“*.txt”));
break;
case 10:
print_r(parse_ini_file(“test.ini”,true));
break;
case 11:
echo tempnam(‘http://localhost/File&#8217;,’TMPO’);
break;
case 12:
$temp = tmpfile();

fwrite($temp, “Testing, testing.”);
//Rewind to the start of file
rewind($temp);
//Read 1k from file
echo fread($temp,1024);

//This removes the file
fclose($temp);
break;
}

?>

2 Comments

Filed under php

PHP optimisation tips revisited

  • echo is faster than print.
  • Use echo’s multiple parameters instead of string concatenation.
  • Use require() instead of require_once() where possible.
  • require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference.
  • String in single quotes (‘) instead of double quotes (“) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string.
  • Since PHP5, the time of when the script started executing can be found in $_SERVER[’REQUEST_TIME’], use this instead of time() or microtime().
  • Error suppression with @ is very slow.

Leave a comment

Filed under php

About PHPJasperXML

 We initialize this project (Actually it is a class) because of we want to develop web report in php easily (The output of report is PDF/XLS because it platform indepent and printer friendly). This project allow php programmer or report designer design php web report easily. Even very junior PHP programmer able to design the PDF/EXCEL report with iReport (java based WYSIWYG report designer), but run natively in PHP. This project is completely difference from php-java bridge, a wrapper class will convered report element from jrxml and pass to tcpdf class.

 

Advantages:

  1. Develop PDF report with iReport, which is fast, flexible and effective
  2. Run natively in PHP, no integration with Java
  3. Integrate to your existing project easily
  4. You can submit whatever parameter into your PDF/EXCEL report easily, either with GET or POST
  5. Open sourced, you can change the library yourself.

Currently this project is consider stable but there are a lot of function in jasper report is not ready yet because compatibility issue between JAVA and PHP. However, you’ll found that it already can create a lot of reports easily.

Sample View : http://www.simit.com.my/download/samplePHPJasperXML.pdf

Why we want to create report in PDF/EXCEL

  1. Web based programming need a standard layout out report, which is fixed and printer friendly. Using traditional HTML method is really hard to design multipage, beautiful and cross platform report.
  2. PDF is industry standard, the font, layout, margin is fixed. No matter at server side, client side and printer it display same result.
  3. PDF working well in all platform
  4. PDF support hyperlink, image, encryption and etc function.
  5. PDF is well known in market, most of the software already pre-install PDF viewer.
  6. PDF support multi-language.

Installation

  1. Download and extract this project into you website root directory (I assume /var/www/PHPJasperXML)
  2. Import sampledb.sql into mysql database, in this project we assume your username=root, password=mysql, database = phpjasperxml. If you use difference user/password/database, you shall change setting in sample1.php and sample2.php.
  3. With your favorite web browser, browse into http://localhost/PHPJasperXML/index.php, test report you like.
  4. Finish.

How to Use This Class

  1. You can use iReport to edit the sample1.jrxml, sample jrxml and see the effect from web browser.
  2. You can use any text editor to edit sample1.php and sample2.php, you will found that integrate the report into your project is like peanut.

Join Development

Currently there is no any external programmer join into this project yet. If you feel interested into this project and willing to give your hand, simply create a topic in this forum: http://www.extraknowledge.org/forum/. Please take note this project use TCPDF heavily.

How To Edit The Report

  1. Download iReport
  2. Use iReport to open sample1.jrxml, sample2.jrxml, sample3.jrxml.
  3. Perform changes and preview the report in iReport.
  4. Preview the report at http://localhost/PHPJasperXML/sample<N>.php

 

1 Comment

Filed under php

Leave a comment

Filed under php

How to sort the GridView data?

Introduction

GridView control has a property called “AllowSorting” which enables us to sort the GridView records. So to enable sorting for GridView, set AllowSorting property of the GridView to true and you will need to also handle theOnSorting event. Setting AllowSorting to true converts the column headers to a clickable link and clicking those headers fires the OnSorting event.

The following code snippet from ASPX page shows how these properties and events are set.

ASPX Page:

 

<asp:GridView ID=”GridView1″ OnSorting=”SortRecords” runat=”server”

AllowSorting=”True” CellPadding=”4″ DataKeyNames=”AutoId” />

CODE Behind:

string _connStr = ConfigurationManager.ConnectionStrings[“ConnStr”].ConnectionString;

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

BindData();

}

}

 

protected void SortRecords(object sender, GridViewSortEventArgs e)

{

string sortExpression = e.SortExpression;

string direction = string.Empty;

if (SortDirection == SortDirection.Ascending)

{

SortDirection = SortDirection.Descending;

direction = ” DESC”;

}

else

{

SortDirection = SortDirection.Ascending;

direction = ” ASC”;

}

DataTable table = this.GetData();

table.DefaultView.Sort = sortExpression + direction;

GridView1.DataSource = table;

GridView1.DataBind();

}

 

private void BindData()

{

// specify the data source for the GridView

GridView1.DataSource = this.GetData();

// bind the data now

GridView1.DataBind();

}

 

/// <summary>

/// Gets or sets the grid view sort direction.

/// </summary>

/// <value>

/// The grid view sort direction.

/// </value>

public SortDirection SortDirection

{

get

{

if (ViewState[“SortDirection”] == null)

{

ViewState[“SortDirection”] = SortDirection.Ascending;

}

return (SortDirection)ViewState[“SortDirection”];

}

set

{

ViewState[“SortDirection”] = value;

}

}

 

private DataTable GetData()

{

DataTable table = new DataTable();

// get the connection

using (SqlConnection conn = new SqlConnection(_connStr))

{

// write the sql statement to execute

string sql = “SELECT AutoId, FirstName, LastName, Age, Active FROM PersonalDetail ORDER By AutoId”;

// instantiate the command object to fire

using (SqlCommand cmd = new SqlCommand(sql, conn))

{

// get the adapter object and attach the command object to it

using (SqlDataAdapter ad = new SqlDataAdapter(cmd))

{

// fire Fill method to fetch the data and fill into DataTable

ad.Fill(table);

}

}

}

return table;

}

In the above code snippet, first we have populated records to the GridView (using BindData method) in the Page_Load event (inside Not IsPostBack, to ensure that data binding happens only if the request is not a postback request).

You may notice that on the .aspx page, we have specified OnSorting event (that fires SortRecords methods) andAllowSorting=true to the GridView. In this case we have set AutoGenerateColumns=true to the GridView, so our GridView columns are automatically generated .In case we are using BoundField or TemplateField, we can use SortExpressionproperty to set the field name to sort on.

When any column of the GridView is clicked, the SortRecords server side method fires that first saves the sort expression and direction (Ascending or Descending order) into the string variable. We have a SortDirection property that saves the current sort direction in the ViewState and based on that the direction string variable is set as ASC or DESC. As the DataSource of this GridView is DataTable so we have used Sort method of its view and set the sort expression. This will sort the rows of the DataTable. After sorting, the GridView data source has been set and the DataBind method has been called.

Now when we run this page, we get the output as shown below.

Conclusion:

Setting AllowSorting=true and handling the OnSorting event, we can sort the records of the GridView.

Leave a comment

Filed under php