pantz.org banner
Create a piechart with PHP
Posted on 11-03-2002 02:30:00 UTC | Updated on 11-03-2002 02:30:00 UTC
Section: /software/php/ | Permanent Link

This code uses data taken from a MYSQL database and makes a piechart from it. I did the MYSQL mods and a guy named Xiao did the pie chart. The PHP install on the webserver has to be compiled with the GD, Freetype2, and libjpeg (libpng looks better for graphs IMHO). To make the graph appear just access it like its a picture file.

<?php

// Example of html to access the bar graph in html: 

/********************************
2D Pie Chart Version 1.0
Programer: Xiao Bin Zhao
E-mail: love1001_98@yahoo.com
Date: 03/31/2001
All Rights Reserved 2001.
********************************/

/*************Configuration Starts Here******************/

$chartTitle = "Percentage of Products in Database"; //pie chart name

/*************************End****************************/

/*****************For Programers Only********************/
$imageWidth = 600; //image width
$imageHeight = 400; //image height
$diameter = 250; //pie diameter
$centerX = 225; //pie center pixels x
$centerY = 225; //pie center pixels y
$labelWidth = 10; //label width, no need to change
/*************************End****************************/

//db connection info.
$dbuser = 'db';

$dbhost = 'database.here.com';

$dbpass = 'poe23451!@#';

$dbname = 'test';

$mysql_link = mysql_connect($dbhost,$dbuser,$dbpass) or die ("Could not connect"); //connect to db

mysql_select_db ($dbname) or die ("DB select failed"); //select db

$query1 = "select productname, count(*) as groupcount from product group by productname"; //get product count by groups of products

$query2 = "select count(*) as countammount from product"; //get the ammount of products in the db

$result1 = mysql_db_query($dbname,$query1); //queryresult1

$result2 = mysql_db_query($dbname,$query2); //queryresult2

$result3 = mysql_db_query($dbname,$query1); //queryresult3

$num_products = mysql_num_rows($result1); //count number of products

while ($row = mysql_fetch_assoc ($result2)) //put total ammount of products in db from query in a var
{
$dataTotal = $row[countammount];
}

function circlePoint( $deg, $dia )
{
$x = cos( deg2rad( $deg ) ) * ( $dia / 2 );
$y = sin( deg2rad( $deg ) ) * ( $dia / 2 );
return array( $x, $y );
}

$im = ImageCreate( $imageWidth, $imageHeight ); //make image area

//color array for chart. addmore colors if you have more data than colors below.
$color[] = ImageColorAllocate( $im, 255, 0, 0 ); //red
$color[] = ImageColorAllocate( $im, 255, 204, 0 );//yellow
$color[] = ImageColorAllocate( $im, 153, 204, 0 );//green
$color[] = ImageColorAllocate( $im, 153, 51, 255 );//purple
$color[] = ImageColorAllocate( $im, 0, 128, 255 );//blue
$color[] = ImageColorAllocate( $im, 255, 0, 128 );//pink
$color[] = ImageColorAllocate( $im, 153, 51, 255 );//purple
$color[] = ImageColorAllocate( $im, 192, 192, 192 );//grey
$color[] = ImageColorAllocate( $im, 204, 204, 0 );
$color[] = ImageColorAllocate( $im, 64, 128, 128 );
$color[] = ImageColorAllocate( $im, 204, 102, 153 );
$white = ImageColorAllocate( $im, 255, 255, 255 );
$black = ImageColorAllocate( $im, 0, 0, 0 );
$grey = ImageColorAllocate( $im, 215, 215, 215 );

ImageFill( $im, 0, 0, $white ); //make image background

$degree = 0;

/**********************************
make the pie chart with percentages
**********************************/

$i=-1; //set color array counter

while ($row = mysql_fetch_assoc ($result1))
{

$i < sizeof( $row ); $i++; //counter for color array

$startDegree = round( $degree );
$degree += ( $row[groupcount] / $dataTotal ) * 360;
$endDegree = round( $degree );

$currentColor = $color[ $i % ( count( $color ) ) ];

ImageArc( $im, $centerX, $centerY, $diameter, $diameter, $startDegree, $endDegree, $currentColor );

list( $arcX, $arcY ) = circlePoint( $startDegree, $diameter );
ImageLine( $im, $centerX, $centerY, floor( $centerX + $arcX ), floor( $centerY + $arcY ), $currentColor );

list( $arcX, $arcY ) = circlePoint( $endDegree, $diameter );
ImageLine( $im, $centerX, $centerY, ceil( $centerX + $arcX ), ceil( $centerY + $arcY ), $currentColor );

$midPoint = round( ( ( $endDegree - $startDegree ) / 2 ) + $startDegree );
list( $arcX, $arcY ) = circlePoint( $midPoint, $diameter / 1.5 );
ImageFillToBorder( $im, floor( $centerX + $arcX ), floor( $centerY + $arcY ), $currentColor, $currentColor );
//joe: i added -6 to center %'s better
ImageString( $im, 2, floor( $centerX + $arcX - 6 ), floor( $centerY + $arcY - 6 ), intval( round( $row[groupcount] / $dataTotal * 100 ) ) . "%", $black );

}

/**********************************
setup for the menu and print title
**********************************/

$labelX = $centerX + $diameter / 2 + 10;
$labelY = $centerY - $diameter / 4;
$titleX = $labelX - $diameter / 4;
$titleY = $centerY - $diameter / 2;
//ImageString( $im, 3, $titleX + 1, $titleY + 1, $chartTitle, $grey );
ImageString( $im, 3, $titleX, $titleY, $chartTitle, $black ); //print chart title
ImageString( $im, 1, $labelX, $titleY + 14, date( "Y-m-d H:i:sa" ), $black ); //print date

/**********************************
make the menu,lables,totals
**********************************/

$i=-1; //set color array counter

while ($row1 = mysql_fetch_assoc ($result3))
{

$i < sizeof( $row1 ); $i++; //counter for color array

$currentColor = $color[ $i % ( count( $color ) ) ];
ImageRectangle( $im, $labelX, $labelY, $labelX + $labelWidth, $labelY + $labelWidth, $black );
ImageFilledRectangle( $im, $labelX + 1, $labelY + 1, $labelX + $labelWidth, $labelY + $labelWidth, $currentColor );
ImageString( $im, 2, $labelX + $labelWidth + 5, $labelY, $row1[productname], $black );
//ImageString( $im, 2, $labelX + $labelWidth + 60, $labelY, $row1[groupcount], $black );
$labelY += $labelWidth + 2;
}

/**********************************
make the total
**********************************/

ImageString( $im, 3, $labelX, $labelY, "Total:", $black );
ImageString( $im, 3, $labelX + $labelWidth + 60, $labelY, $dataTotal, $black );
//ImageString( $im, 2, $labelX, $labelY + 15, $logo, $black );

Header( "Content-type: image/jpeg" ); //output image
Imagejpeg( $im );
ImageDestroy( $im ); //remove image from memory
?>

Del.icio.us! | Digg Me! | Reddit!

Related stories

PHP tuning tips
Posted on 11-03-2002 02:14:00 UTC | Updated on 11-03-2002 02:14:00 UTC
Section: /software/php/ | Permanent Link

PHP scripts take a lot more horsepower (cpu and ram) to run that regular static webpages. All code has to be processed on the fly when the page request is made. The ability to have a dynamic website is what makes investing in more cpu and ram worth it. Below are some tips on how to get the best performance when using PHP.

1. The bottle neck for PHP scripts is the CPU unlike HTML pages. So get the fastest CPU you can afford. If your going to be doing static HTML files try to get as much ram as you can afford.

2. Enable HTML compression with ob_gzhandler(). This function is designed to check the Content-Encoding header for deflate or gzip, and automatically compresses the output using the supported encoding. Using it is as simple as turning output buffering on, and setting it as the output handler function: ob_start("ob_gzhandler"); or in the php.ini file with the line: output_handler = ob_gzhandler;.You might want to test this first using ob_start to see if it helps with the download time on larger text output. Also only use this on PHP version 4.1.0 or above and you will need zlib support compiled in to PHP. gzip'ed output is supported by IE 4.0 and higher, Netscape 4.x and Mozilla. Also look into turning compression on with your webserver. For example with lighttpd there is a module called mod_compress. It will compress all pages requested from the webserver and put them in a compressed file on the webserver. Then that file is served out instead of compressing the file each time a request comes in.

3. Use PHP caching software to speed up your scripts.These cache the PHP scripts so they don't have to be compiled everytime they are executed. Some examples of this software are: PHP Accelerator,Zend Accelerator,Afterburner Cache,Turck MMCache, and APC. I've read PHP Accelerator is the best. Most will give a 25-100% improvement in speed. If you run PHP scripts that access a database backend you also might want to check out memchached. Memcached is a distributed memory object caching system intended for use in speeding up dynamic web applications by alleviating database load.

4. Use version 2.0 of apache if you can and compile PHP into it. Apache 2.0 uses threads and improves speed.

5. Switch from file based sessions to shared memory sessions. Compile PHP with the --with-mm option and set session.save_handler=mm in php.ini. Use this feature on PHP 4.2.0 or above.

6. Use output buffering via the ob_start() function. This may speed up your PHP code by 5-15% if you like to use print or echo statements in your code. If your already using ob_gzhandler (mentioned above) as a function or as a output handler then you don't need to use ob_start because it's already being used.

7. The PHP development team recommends compiling PHP4 with the following settings --enable-inline-optimization --disable-debug.

Del.icio.us! | Digg Me! | Reddit!

Related stories

A form that sends an e-mail with PHP
Posted on 11-03-2002 02:13:00 UTC | Updated on 11-03-2002 02:13:00 UTC
Section: /software/php/ | Permanent Link

This page contains 3 pages of info broken up into 3 boxes below. The first section you fill out the form. The second section you check what you filled out. On the third section the email gets sent. The javascript checks that certian boxes are filled out. The PHP code will update the form fields if you go back and forth from the check page and the entry page. Put these three different sections below in three different files. The php code is very simple and not very good but it works.

Page 1

<?
// Initialize session
session_start();

?>

<html>

<script language="JavaScript">
<!--

function checkFields() {

if (document.metsign.billtoccname.value == 0)
       {
          alert("Please provide us with the name that appears on the Credit Card.\n"); 
          return false;
       }
if (document.metsign.billtoaddress1.value == 0)
       {
          alert("Please provide us with the billing address of the Credit Card.\n");    
          return false;
       }
if (document.metsign.billtocity.value == 0)
       {
          alert("Please provide us with your city.\n");
          return false;
       }
if (document.metsign.billtostate.value == 'select_state')
       {
          alert("Please provide us with your state.\n");
          return false;
       }
if (document.metsign.billtozip.value == 0)
       {
          alert("Please provide us with your zip.\n");
          return false;
       }
if (document.metsign.billtophone.value == 0)
       {
          alert("Please provide us with your phone number.\n");
          return false;
       }

if (!document.metsign.cctype[0].checked && !document.metsign.cctype[1].checked && !document.metsign.cctype[2].checked)
	 {
	  alert("Please choose a Credit Card type.\n");
	  return false;
         }

if (document.metsign.ccnumber.value == 0)
       {
          alert("Please provide us with your credit card number.\n");
          return false;
       }

if (document.metsign.ccexpmonth.value == 'select_month')
       {
          alert("Please provide us with your Credit Cards expiration month.\n");
          return false;
       }
if (document.metsign.ccexpyear.value == 'select_year') 
       {
          alert("Please provide us with your Credit Cards expration year\n");
          return false;
       }
if (document.metsign.billtosubscription.value == 'select_sub')
       {
          alert("Please provide us with your subscription type.\n");
          return false;
       }

}

// -->

</script>

<form action="formpg2.php" method="POST" name="metsign">

Please provide us with the credit card information below.<br><br>

<b>User-Info:</b><br><br>

First Name<input type="text" name="userfirstname" size="29" maxlength="29"<? if (session_is_registered("userfirstname") == true) { print "value =\"$userfirstname\""; 
} else { print "value=\"\""; } ?>><br><br>
Last Name<input type="text" name="userlastname" size="29" maxlength="29"<? if (session_is_registered("userlastname") == true) { print "value =\"$userlastname\""; } 
else { print "value=\"\""; } ?>><br><br>

<b>Bill-To:</b><br><br>

Company Name<input type="text" name="billtocompanyname" size="29" maxlength="29"<? if (session_is_registered("billtocompanyname") == true) { print "value 
=\"$billtocompanyname\""; } else { print "value=\"\""; } ?>><br><br>

Name on Credit Card<input type="text" name="billtoccname" size="29" maxlength="29"<? if (session_is_registered("billtoccname") == true) { print "value =\"$firstname 
$billtoccname\""; } else { print "value=\"\""; } ?>><br><br>

Address 1<input type="text" name="billtoaddress1" size="29" maxlength="29"<? if (session_is_registered("billtoaddress1") == true) { print "value 
=\"$billtoaddress1\""; } else { print "value=\"\""; } ?>><br><br>

Address 2<input type="text" name="billtoaddress2" size="29" maxlength="29"<? if (session_is_registered("billtoaddress2") == true) { print "value 
=\"$billtoaddress2\""; } else { print "value=\"\""; } ?>><br><br> 

City<input type="text" name="billtocity" size="29" maxlength="29"<? if (session_is_registered("billtocity") == true) { print "value =\"$billtocity\""; } else { print 
"value=\"\""; } ?>><br><br> 

State<SELECT NAME="billtostate">
<OPTION selected value="select_state">Select</option>

<option value="AK">AK</option>
<option value="AL">AL</option>
<option value="AR">AR</option>
<option value="AZ">AZ</option>
<option value="CA">CA</option>

<option value="CO">CO</option>
<option value="CT">CT</option>
<option value="DC">DC</option>
<option value="DE">DE</option>
<option value="FL">FL</option>

<option value="GA">GA</option>
<option value="HI">HI</option>
<option value="IA">IA</option>
<option value="ID">ID</option>
<option value="IL">IL</option>

<option value="IN">IN</option>
<option value="KS">KS</option>
<option value="KY">KY</option>
<option value="LA">LA</option>
<option value="MA">MA</option>

<option value="MD">MD</option>
<option value="ME">ME</option>
<option value="MI">MI</option>
<option value="MN">MN</option>
<option value="MO">MO</option>

<option value="MS">MS</option>
<option value="MT">MT</option>
<option value="NC">NC</option>
<option value="ND">ND</option>
<option value="NE">NE</option>

<option value="NH">NH</option>
<option value="NJ">NJ</option>
<option value="NM">NM</option>
<option value="NV">NV</option>
<option value="NY">NY</option>

<option value="OH">OH</option>
<option value="OK">OK</option>
<option value="OR">OR</option>
<option value="PA">PA</option>
<option value="RI">RI</option>

<option value="SC">SC</option>
<option value="SD">SD</option>
<option value="TN">TN</option>
<option value="TX">TX</option>
<option value="UT">UT</option>

<option value="VA">VA</option>
<option value="VT">VT</option>
<option value="WA">WA</option>
<option value="WI">WI</option>
<option value="WV">WV</option>

<option value="WY">WY</option>
</select><br><br>

Zip Code<input type="text" name="billtozip" size="10" maxlength="12"<? if (session_is_registered("billtozip") == true) { print "value =\"$billtozip\""; } else { 
print "value=\"\""; } ?>><br><br> 

Phone Number<input type="text" name="billtophone" size="15" maxlength="15"<? if (session_is_registered("billtophone") == true) { print "value =\"$billtophone\""; } 
else { print "value=\"\""; } ?>><br><br>


Type of credit card<br><br>

Visa<input type="radio" name="cctype" value="Visa"><br>

Mastercard<input type="radio" name="cctype" value="Mastercard"><br>

Discover<input type="radio" name="cctype" value="Discover"><br><br>

Credit Card Number<input type="text" name="ccnumber" size="16" maxlength="16"<? if (session_is_registered("ccnumber") == true) { print "value =\"$ccnumber\""; } else 
{ print "value=\"\""; } ?>><br><br>

Credit Card Expiration <select name="ccexpmonth">
<OPTION selected value="select_month">Select Month</option>

<OPTION value="1">1</option>
<OPTION value="2">2</option>
<OPTION value="3">3</option>
<OPTION value="4">4</option>
<OPTION value="5">5</option>

<OPTION value="6">6</option>
<OPTION value="7">7</option>
<OPTION value="8">8</option>
<OPTION value="9">9</option>
<OPTION value="10">10</option>

<OPTION value="11">11</option>
<OPTION value="12">12</option>
</select>

<select name="ccexpyear">
<OPTION selected value="select_year">Select Year</option>

<OPTION value="2001">2001</option>
<OPTION value="2002">2002</option>
<OPTION value="2003">2003</option>
<OPTION value="2004">2004</option>
<OPTION value="2005">2005</option>

<OPTION value="2006">2006</option>
<OPTION value="2007">2007</option>
<OPTION value="2008">2008</option>
<OPTION value="2009">2009</option>
<OPTION value="2010">2010</option>

<OPTION value="2011">2011</option>
<OPTION value="2012">2012</option>
</select><br><br>

<select name="billtosubscription">
<OPTION selected value="select_sub">Select Subscription</option>

<OPTION value="Q1">Quarterly Subscription</option>
<OPTION value="Y1">Yearly Subscription</option>
</select><br><br>

<center><input type="submit" name="submit" value="Next -->" onClick="return checkFields();"></center> 

</form>
</html>

Page 2

<?
// Initialize session
session_start();

session_register("userfirstname");
$GLOBALS['userfirstname']=$HTTP_POST_VARS['userfirstname'];

session_register("userlastname");
$GLOBALS['userlastname']=$HTTP_POST_VARS['userlastname'];

session_register("billtocompanyname");
$GLOBALS['billtocompanyname']=$HTTP_POST_VARS['billtocompanyname'];

session_register("billtoccname");
$GLOBALS['billtoccname']=$HTTP_POST_VARS['billtoccname'];

session_register("billtoaddress1");
$GLOBALS['billtoaddress1']=$HTTP_POST_VARS['billtoaddress1'];

session_register("billtoaddress2");
$GLOBALS['billtoaddress2']=$HTTP_POST_VARS['billtoaddress2'];

session_register("billtocity");
$GLOBALS['billtocity']=$HTTP_POST_VARS['billtocity'];

session_register("billtostate");
$GLOBALS['billtostate']=$HTTP_POST_VARS['billtostate'];

session_register("billtozip");
$GLOBALS['billtozip']=$HTTP_POST_VARS['billtozip'];

session_register("billtophone");
$GLOBALS['billtophone']=$HTTP_POST_VARS['billtophone'];

session_register("cctype");
$GLOBALS['cctype']=$HTTP_POST_VARS['cctype'];

session_register("ccnumber");
$GLOBALS['ccnumber']=$HTTP_POST_VARS['ccnumber'];

session_register("ccexpmonth");
$GLOBALS['ccexpmonth']=$HTTP_POST_VARS['ccexpmonth'];

session_register("ccexpyear");
$GLOBALS['ccexpyear']=$HTTP_POST_VARS['ccexpyear'];

session_register("billtosubscription");
$GLOBALS['billtosubscription']=$HTTP_POST_VARS['billtosubscription'];


?>

<html><center><h3>After you have verfied this information is correct please click the finish button.</h3></center><br>
<center><h3>If you need to make changes click the back button on your browser</h3></center><br>

<?
print "<center><table border=\"1\">

<tr><td><b>Users First Name:</b> $userfirstname</td></tr>

<tr><td><b>Users Last Name:</b> $userlastname</td></tr>

<tr><td><b>Met Cert #:</b> $metcertnum</td></tr>

<tr><td><b>Company Name:</b> $billtocompanyname</td></tr>

<tr><td><b>Name on Credit Card:</b> $billtoccname</td></tr> <tr><td><b>Address 1:</b> 
$billtoaddress1</td></tr>

<tr><td><b>Address 2:</b> $billtoaddress2</td></tr> <tr><td><b>City:</b> $billtocity</td></tr>

<tr><td><b>State:</b> $billtostate</td></tr> <tr><td><b>Zip:</b> $billtozip</td></tr>

<tr><td><b>Phone Number:</b> $billtophone</td></tr> <tr><td><b>Credit Card Type:</b> 
$cctype</td></tr>

<tr><td><b>Credit Card Number:</b> $ccnumber</td>

<tr><td><b>Credit Card Expration:</b> $ccexpmonth/$ccexpyear</td></tr>

<tr><td><b>Subscription Type:</b> $billtosubscription</td></tr>

</table></center>

<center> <form><input type=\"button\" name=\"Edit Information\" value=\"Finish\" onClick=\"document.location.href='formpg3.php';\">

<html>"

?>

Page 3

<? 
session_start(); // initialize session

// setup email addributes \\
$testemail = "ccinfo@here.com";
$emailsubject = "Form Information";
$emailfrom = "From: ccinfo@here.com";
$body = "
-=User Info=-\n\n
Name: $firstname $lastname\n

-=Bill-To Info=-\n\n
Bill-To Company Name: $billtocompanyname\n
Bill-To Credit Card Name: $billtoccname\n
Bill-To Address1: $billtoaddress1\n
Bill-To Address2: $billtoaddress2\n
Bill-To City: $billtocity\n
Bill-To State: $billtostate\n
Bill-To Zip: $billtozip\n
Bill-To Phone: $billtophone\n
Bill-To Credit Card Type: $cctype\n
Bill-To Credit Card Number: $ccnumber\n
Bill-To Credit Card Exp: $ccexpmonth/$ccexpyear\n
Bill-To Subscription: $billtosubscription\n
";

//send the email. I suggest if your sending real credit card info you 
//encrypt the e-mail. see www.pantz.org for an example
mail ($testemail, $emailsubject, $body, $emailfrom);

print "<html><center>Thanks for filling out the form.</center></html>";

?>

Del.icio.us! | Digg Me! | Reddit!

Related stories


RSS Feed RSS feed logo
About


3com
3ware
alsa
alsactl
alsamixer
amd
android
apache
areca
arm
ati
auditd
awk
badblocks
bash
bind
bios
bonnie
cable
carp
cat5
cdrom
cellphone
centos
chart
chrome
cifs
cisco
cloudera
comcast
commands
comodo
compiz-fusion
corsair
cpufreq
cpufrequtils
cpuspeed
cron
crontab
crossover
cu
cups
cvs
database
dbus
dd
dd_rescue
ddclient
debian
decimal
dhclient
dhcp
diagnostic
diskexplorer
disks
dkim
dns
dos
dovecot
drac
dsniff
dvdauthor
e-mail
echo
editor
emerald
ethernet
expect
ext3
ext4
fat32
fedora
fetchmail
fiber
filesystems
firefox
firewall
flac
flexlm
floppy
flowtools
fonts
format
freebsd
ftp
gdm
gmail
gnome
greasemonkey
greylisting
growisofs
grub
hacking
hadoop
harddrive
hba
hex
hfsc
html
html5
http
https
idl
ie
ilo
intel
ios
iperf
ipmi
iptables
ipv6
irix
javascript
kde
kernel
kickstart
kmail
kprinter
krecord
kubuntu
kvm
lame
ldap
linux
logfile
lp
lpq
lpr
maradns
matlab
memory
mencoder
mhdd
mkinitrd
mkisofs
moinmoin
motherboard
mouse
movemail
mplayer
multitail
mutt
myodbc
mysql
mythtv
nagios
nameserver
netflix
netflow
nginx
nic
ntfs
ntp
nvidia
odbc
openbsd
openntpd
openoffice
openssh
openssl
opteron
parted
partimage
patch
perl
pf
pfflowd
pfsync
photorec
php
pop3
pop3s
ports
postfix
power
procmail
proftpd
proxy
pulseaudio
putty
pxe
python
qemu
r-studio
raid
recovery
redhat
router
rpc
rsync
ruby
saltstack
samba
schedule
screen
scsi
seagate
seatools
sed
sendmail
sgi
shell
siw
smtp
snort
solaris
soundcard
sox
spam
spamd
spf
sql
sqlite
squid
srs
ssh
ssh.com
ssl
su
subnet
subversion
sudo
sun
supermicro
switches
symbols
syslinux
syslog
systemrescuecd
t1
tcpip
tcpwrappers
telnet
terminal
testdisk
tftp
thttpd
thunderbird
timezone
ting
tls
tools
tr
trac
tuning
tunnel
ubuntu
unbound
vi
vpn
wget
wiki
windows
windowsxp
wireless
wpa_supplicant
x
xauth
xfree86
xfs
xinearama
xmms
youtube
zdump
zeromq
zic
zlib