<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.in/ */ echo ""; ?>
Saturday, April 20, 2013
Dynamic selection of year list in php
To avoid the need to write up to many lines in your HTML forms. PHP for loop helps us for that. Use below simple code for that
Friday, April 19, 2013
Generate a CSV file from MySQL records
This class can generate a CSV file from MySQL query results.
It can connect to a given MySQL database and execute a SQL query.
The class can generate a CSV file from the query results.
The CSV file may have headers generated from the query result column names or use custom names.
The generated CSV file may be save to a file, served for download or displayed on a Web page.
class.select2csv.php
<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.in/ */ /** * select2csv * * @package MySQL Select CSV Dump * @author Mark Berube * @license Distributed under GNU/GPL * @version 0.1 * @access public */ class select2csv{ var $result; var $result_col_headers = array(); var $qry = false; var $conn_to_db; var $conn_array; var $error = false; var $debug = false; var $use_first_line_header_row = true; var $csv; var $delim; var $output_file; var $delivery;// 'local_file', 'passthru', 'print' /** * select2csv::__construct() * @desc object constructor * @param array $conn_array * @param bool $conn_to_db * @return void */ function __construct($conn_array=false,$conn_to_db=false){ $this->conn_to_db = $conn_to_db; $this->conn_array = $conn_array; } /** * select2csv::set_qry() * @desc Sets the MySQL qry to be executed * @param string $qry * @return void */ function set_qry($qry){ $this->qry = $qry; } /** * select2csv::set_delim() * @desc Sets the Delimiter for the CSV output * @param string $delim * @return void */ function set_delim($delim){ $this->delim = $delim; } /** * select2csv::set_custom_headers() * @desc Sets the Delimiter for the CSV output * @param array $headers_arr * @return void */ function set_custom_headers($headers_arr){ $this->result_col_headers = $headers_arr; } /** * select2csv::first_line_headers() * @desc Disables creating the first line headers row * @return void */ function remove_header_line(){ $this->use_first_line_header_row = false; } /** * select2csv::debug() * @desc If function is called with no args it will echo errors if something is missing. Default is off * @param bool $val * @return void */ function debug($val=true){ $this->debug = $val; } /** * select2csv::execute() * @desc execute query object after all parameters set * @param string $action * @return array if action is select else true or false */ function execute($action='s'){ if($this->conn_to_db){ $conn_array = $this->conn_array; $conn = mysql_connect($conn_array['host'], $conn_array['user'], $conn_array['pw'])or die("Unable to connect to MYSQL because: ".mysql_error()); $db_select = mysql_select_db($conn_array['db'],$conn) or die("Could not select '".$conn_array['db']."' database because: ".mysql_error()); } //select will return array, either empty or populated $this->result_val_type = 'array'; $this->result = $this->db_qry_get_rows(); if(empty($this->result_col_headers)){ $this->result_col_headers = $this->db_qry_get_headers(); } $this->build_csv(); if($this->conn_to_db){ mysql_close($conn); } if($this->debug){ if($this->error){ echo $this->error; return false; } } } function build_csv(){ //$result = $this->result; $NumFields = count($this->result_col_headers); $header_row = ""; $data_rows = ""; if($this->use_first_line_header_row){ /////////////////////// //build the headers from array keys /////////////////////// $col = 1; foreach ($this->result_col_headers as $header){ $header_row .= $header; $header_row .= ($col < $NumFields) ? $this->delim : "\r\n"; $col++; } } /////////////////////// //Now Get the data rows /////////////////////// foreach($this->result as $row){ //print_r($row); $col = 1;//reset foreach ($row as $data){ $data_rows .= trim($data); $data_rows .= ($col < $NumFields) ? $this->delim : "\r\n"; $col++; } } $this->csv = $header_row . $data_rows; unset($header_row,$data_rows); } /** * select2csv::db_qry_get_rows() * @desc Assembles 'select' qry results to a 2-dim assoc array. This function is called with the 's' action * @return array if executed without error else false */ function db_qry_get_rows(){ $rows = array(); if($this->qry == false){ $this->error = "You must set a query (using set_qry()) before executing a 'select'"; return false; } $res = mysql_query($this->qry); if($res){ $cnt = 0; while($row = mysql_fetch_assoc($res)){ foreach ($row as $key => $val){ $rows[$cnt][$key] = $val; } $cnt++; } mysql_free_result($res); } return $rows; } /** * select2csv::db_qry_get_headers() * @desc Grabs this first record result and extracts the array keys for use as column headers...just for ease of access * @return array */ function db_qry_get_headers(){ $headers = array(); if(is_array($this->result[0])){ if(empty($this->result[0])){ return $headers; }else{ foreach ($this->result[0] as $key => $value) { $headers[] = $key; } } return $headers; } return false; } /** * select2csv::output() * @desc Delivers csv content in one of three ways: creation of local file, print to the browser window, or passthru for download * @param string $delivery * @param string $fname * @param string $local_path * @return void */ function output($delivery, $fname='', $local_path='.'){ switch($delivery){ case 'local_file': file_put_contents($local_path.'/'.$fname,$this->csv); break; case 'passthru': $tmp = 'Select2CSV_Dump.csv'; file_put_contents($tmp,$this->csv); $file_size = filesize($tmp); if ($fp = fopen($tmp, 'rb')) { Header('Content-Disposition: attachment; filename="'.$fname.'"'); Header('Content-Length: '.$file_size); fpassthru($fp); } else { echo "cannot find tmp file: check that the script has write permission to the containing folder"; } break; case 'print': echo ''."\n".$this->csv.''; break; } } } ////////////////// // Example usage ////////////////// ini_set('display_errors','On'); $db_creds = array( 'db' => "db_name", 'user' => "myusername", 'pw' => "mypassword", 'host' => "localhost" ); $csv = new select2csv($db_creds,true); $csv->set_qry("SELECT fname,lname,email,role FROM users"); //$csv->remove_header_line();//disables using a column header row at all $csv->set_custom_headers(array('First','Last','EMail','Role'));//default is to use the field names from query as column headers $csv->set_delim('|'); $csv->execute(); /////////////////// // 3 methods of delivery show below /////////////////// //$csv->output('passthru','csvtest.csv'); $csv->output('print'); //$csv->output('local_file','csvtest.csv','./tmp'); ?>
By: 4evertutorials
On 4/19/2013
Forex Class for PHP 5
This class can convert money amounts between currencies using iGoogle calculator API.
It can send a HTTP request to the iGoogle calculator API to convert a given money amount between to given currencies.
The class parses the response and returns an array with the original and converted values and currency symbols, the current time and the API URL.
class.forex.php
<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.in/ */ /** * Foreign Exchange Class | PHP 5 * Build 2013.01.14 * * Copyright (c) 2013 * Jonathan Discipulo* http://jondiscipulo.com/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * http://www.gnu.org/copyleft/lesser.html * **/ // }} // {{ Forex class Forex { private $amount, $from, $to; protected $api, $query; public $result; // }} // {{ Constructor public function __construct() { $this->api = 'http://www.google.com/ig/calculator'; } // }} // {{ Convert public function convert( $amount, $from='USD', $to='USD' ) { $this->amount = $amount; $this->from = $from; $this->to = $to; $this->query = '?hl=en&q=' . $this->amount . $this->from . '%3D%3F' . $this->to; $content = file_get_contents( $this->api . $this->query ); $this->result = $this->parse( $content ); } // }} // {{ Get Result public function get( $string='converted' ) { $array = $this->result; return $array[$string]; } // }} // {{ Get Result Array public function getResultArray() { return $this->result; } // }} // {{ Parse private function parse( $string ) { if (!empty($string)) { $data = explode( '"', $string ); $object = explode( ' ', $data[3]); $result = array( 'from' => $this->from, 'to' => $this->to, 'amount' => $this->amount, 'converted' => $object[0], 'stamp' => gmdate('Y/m/d H:i:s') . ' UTC', 'api' => $this->api ); } else { $result = null; } return $result; } // }} // {{ Magic Method: Sleep public function __sleep() { // reserved for codes to run when in sleep } // }} // {{ Magic Method: Wake Up public function __wakeup() { // reserved for codes to run when after sleep } // }} // {{ Destructor public function __destruct() { // reserved for codes to run when this object is destructed if (isset($this->amount)) unset($this->amount); if (isset($this->from)) unset($this->from); if (isset($this->to)) unset($this->to); if (isset($this->result)) unset($this->result); } } ?>
sample.php
<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.in/ */ require_once('class.forex.php'); $forex = new Forex(); $forex->convert( '1', 'USD', 'PHP' ); echo $forex->get('from') . ' ' . $forex->get('amount') . ' is equal to ' . $forex->get('to') . ' ' . $forex->get('converted') . ' as of ' . $forex->get('stamp') . '
'; echo ""; print_r( $forex->getResultArray() ); echo " "; ?>
By: 4evertutorials
On 4/19/2013
class_exists() function
The class_exists() function is used to determine whether or not a class is defined in the script. It returns a boolean value of either TRUE or FALSE.
example.php
<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.in/ */ include_once("cart.php"); if(class_exists("cart")){ $shopping_cart = new cart(); echo $shopping_cart->store; } else { echo '"cart" class does not exist'; } ?>
cart.php
<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.in/ */ class cart { public $store = "Spacely Sprockets"; public $items = array(); } ?>
By: 4evertutorials
On 4/19/2013
Saturday, April 13, 2013
Handle csv file using php
Assume, I got the following content in my csv file:
You can use fgetcsv to parse a CSV file without having to worry about parsing it yourself.
example from php.net
"data", "data1", "data2", "data3"
"data", "data1", "data2", "data3"
"data", "data1", "data2", "data3"
You can use fgetcsv to parse a CSV file without having to worry about parsing it yourself.
example from php.net
<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.in/ */ $row = 1; if (($handle = fopen("test.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); echo "$num fields in line $row:
\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . " \n"; } } fclose($handle); } ?>
By: 4evertutorials
On 4/13/2013
Subscribe to:
Posts (Atom)