sponsor

Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Monday, January 12, 2009

how to get number of days in the month with php

if you want to know number of days in the month with php, you can call function cal_days_in_month()
this function returns the number of days in a given month, based on the calendar, month, and year that you specify

the format of this function is
Cal_days_in_month (calendar, Month, year)
This function have three parameters,
  • calendar, you can fill this parameter with CAL_GREGORIAN
  • month, you can fill this parameter with month (1 - 12)
  • year, you can fiil this parameter with 4 digits of year (2008)
example :
$days = cal_days_in_month(CAL_GREGORIAN, 1, 2009) ;
echo "In January 2009 there were $days days";
?>

that example will display
In january 2009 there were 31 days

Tuesday, February 19, 2008

Javascript Explode Implode

JavaScript equivalent of PHP explode function

In PHP we can easily break a long string into smaller parts by using the explode() function of PHP. In run rime, this function works like this:

$string="My Name Is Wahyu Pramusinto";
$string2=explode(" ", $string);


After the execution of the second command the variable $string2 is an array such that,

$string2[0]="My"
$string2[1]="Name"
$string2[2]="Is"
$string2[3]="Wahyu"
$string2[4]="Pramusinto"

and so on. So how do we do it in JavaScript. In JavaScript there is a split() function that achieves the same objective, although the syntax is a bit different.

var string="My Name Is Wahyu Pramusinto";
var string2=string.split(" ");

Now the variable string2 has all those words.



Wednesday, January 30, 2008

Introduction CakePHP

Introduction to CakePHP
Section 1
What is CakePHP?

CakePHP is a free open-source rapid development framework for PHP. Its a structure of libraries, classes and run-time infrastructure for programmers creating web applications originally inspired by the Ruby on Rails framework. Our primary goal is to enable you to work in a structured and rapid manner - without loss of flexibility.
Section 2
Why CakePHP?

CakePHP has several features that make it a great choice as a framework for developing applications swiftly and with the least amount of hassle. Here are a few in no particular order:

1.

Active, friendly community
2.

Flexible Licensing
3.

Compatibility with PHP4 and PHP5
4.

Integrated CRUD for database interaction and simplified queries
5.

Application Scaffolding
6.

Model View Controller (MVC) Architecture
7.

Request dispatcher with good looking, custom URLs
8.

Built-in Validation
9.

Fast and flexible templating (PHP syntax, with helpers)
10.

View Helpers for AJAX, Javascript, HTML Forms and more
11.

Security, Session, and Request Handling Components
12.

Flexible access control lists
13.

Data Sanitization
14.

Flexible View Caching
15.

Works from any web site subdirectory, with little to no Apache configuration involved

Section 3
History of CakePHP

In 2005, Michal Tatarynowicz wrote a minimal version of a Rapid Application Framework in PHP. He found that it was the start of a very good framework. Michal published the framework under the MIT license, dubbing it Cake, and opened it up to a community of developers, who now maintain Cake under the name CakePHP.
print chapter

source : http://manual.cakephp.org/chapter/intro, ajax

Monday, January 28, 2008

CodeIgniter

Welcome to CodeIgniter

CodeIgniter is an Application Development Framework - a toolkit - for people who build web sites using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task.

Please read the Introduction section of the User Guide to learn the broad concepts behind CodeIgniter, then read the Getting Started page.
Who is CodeIgniter For?

CodeIgniter is right for you if:

* You want a framework with a small footprint.
* You need exceptional performance.
* You need broad compatibility with standard hosting accounts that run a variety of PHP versions and configurations.
* You want a framework that requires nearly zero configuration.
* You want a framework that does not require you to use the command line.
* You want a framework that does not require you to adhere to restrictive coding rules.
* You are not interested in large-scale monolithic libraries like PEAR.
* You do not want to be forced to learn a templating language (although a template parser is optionally available if you desire one).
* You eschew complexity, favoring simple solutions.
* You need clear, thorough documentation.

http://codeigniter.com/user_guide/

Friday, October 26, 2007

Fungsi PHP untuk menghitung umur

Umur seseorang dihitung berdasarkan perbedaan tanggal lahirnya dengan tanggal sekarang. Kali ini saya akan memberikan fungsi PHP untuk menghitung umur.


//sebuah function dengan nama hitUmur dan sebuah parameter
function hitUmur($tgllahir) {
$tgl = explode("-", $tgllahir);
// memecah $tgllahir yang tadinya YYYY-MM-DD menjadi array
// $tgl[0] = tahun (YYYY)
// $tgl[a] = bulan (MM)
// $tgl[2] = hari (DD)

$umur = date("Y") - $tgl[0]; //ini untuk ngitung umurnya

if(($tgl[1] > date("m")) || ($tgl[1] == date("m") && date("d") < $tgl[2])) //ngecek apakah tgl lahir dan bulannya belum lewat?
{

$umur -= 1;
}
return $umur;
}

//cara mengakses fungsi
$tgllahirku = "1980-10-12";
echo hitUmur($tgllahirku);
?>

Wednesday, October 3, 2007

Instalasi PHP, APACHE, MYSQL

bagi anda yang mau instalasi php, apache dan mysql satu-persatu. Bisa diwonload tutorialnya di sini. Tutorial berbentuk file swf....
1. Untuk instalasi di Windows, http://www.megaupload.com/?d=28V56YG8
2. Untuk instalasi di Linux, http://www.megaupload.com/?d=OGGHZH6S

Semoga tutorial di atas dapat membantu.....

Wednesday, September 19, 2007

Using ADOdb with PHP and Oracle: an advanced tutorial

1. Introduction

Oracle is the most popular commercial database used with PHP. There are many ways of accessing Oracle databases in PHP. These include:

* The oracle extension
* The oci8 extension
* PEAR DB library
* ADOdb library

The wide range of choices is confusing to someone just starting with Oracle and PHP. I will briefly summarize the differences, and show you the advantages of using ADOdb.

First we have the C extensions which provide low-level access to Oracle functionality. These C extensions are precompiled into PHP, or linked in dynamically when the web server starts up. Just in case you need it, here's a guide to installing Oracle and PHP on Linux.
Oracle extension Designed for Oracle 7 or earlier. This is obsolete.
Oci8 extension Despite it's name, which implies it is only for Oracle 8i, this is the standard method for accessing databases running Oracle 8i, 9i or 10g (and later).

Here is an example of using the oci8 extension to query the emp table of the scott schema with bind parameters:

$conn = OCILogon("scott","tiger", $tnsName);

$stmt = OCIParse($conn,"select * from emp where empno > :emp order by empno");
$emp = 7900;
OCIBindByName($stmt, ':emp', $emp);
$ok = OCIExecute($stmt);
while (OCIFetchInto($stmt,$arr)) {
print_r($arr);
echo "
";
}

This generates the following output:
Array ( [0] => 7902 [1] => FORD [2] => ANALYST [3] => 7566 [4] => 03/DEC/81 [5] => 3000 [7] => 20 ) Array ( [0] => 7934 [1] => MILLER [2] => CLERK [3] => 7782 [4] => 23/JAN/82 [5] => 1300 [7] => 10 )

We also have many higher level PHP libraries that allow you to simplify the above code. The most popular are PEAR DB and ADOdb. Here are some of the differences between these libraries:
Feature PEAR DB 1.6 ADOdb 4.52
General Style Simple, easy to use. Lacks Oracle specific functionality. Has multi-tier design. Simple high-level design for beginners, and also lower-level advanced Oracle functionality.
Support for Prepare Yes, but only on one statement, as the last prepare overwrites previous prepares. Yes (multiple simultaneous prepare's allowed)
Support for LOBs No Yes, using update semantics
Support for REF Cursors No Yes
Support for IN Parameters Yes Yes
Support for OUT Parameters No Yes
Schema creation using XML No Yes, including ability to define tablespaces and constraints
Provides database portability features No Yes, has some ability to abstract features that differ between databases such as dates, bind parameters, and data types.
Performance monitoring and tracing No Yes. SQL can be traced and linked to web page it was executed on. Explain plan support included.
Recordset caching for frequently used queries No Yes. Provides great speedups for SQL involving complex where, group-by and order-by clauses.
Popularity Yes, part of PEAR release Yes, many open source projects are using this software, including PostNuke, Xaraya, Mambo, Tiki Wiki.
Speed Medium speed. Very high speed. Fastest database abstraction library available for PHP. Benchmarks are available.
High Speed Extension available No Yes. You can install the optional ADOdb extension, which reimplements the most frequently used parts of ADOdb as fast C code. Note that the source code version of ADOdb runs just fine without this extension, and only makes use of the extension if detected.

PEAR DB is good enough for simple web apps. But if you need more power, you can see ADOdb offers more sophisticated functionality. The rest of this article will concentrate on using ADOdb with Oracle. You can find out more about connecting to Oracle later in this guide.
ADOdb Example

In ADOdb, the above oci8 example querying the emp table could be written as:

include "/path/to/adodb.inc.php";
$db = NewADOConnection("oci8");
$db->Connect($tnsName, "scott", "tiger");

$rs = $db->Execute("select * from emp where empno>:emp order by empno",
array('emp' => 7900));
while ($arr = $rs->FetchRow()) {
print_r($arr);
echo "
";
}

The Execute( ) function returns a recordset object, and you can retrieve the rows returned using $recordset->FetchRow( ).

If we ignore the initial connection preamble, we can see the ADOdb version is much easier and simpler:
Oci8 ADOdb

$stmt = OCIParse($conn,
"select * from emp where empno > :emp");
$emp = 7900;
OCIBindByName($stmt, ':emp', $emp);
$ok = OCIExecute($stmt);

while (OCIFetchInto($stmt,$arr)) {
print_r($arr);
echo "
";
}



$recordset = $db->Execute("select * from emp where empno>:emp",
array('emp' => 7900));

while ($arr = $recordset->FetchRow()) {
print_r($arr);
echo "
";
}


2. ADOdb Query Semantics

You can also query the database using the standard Microsoft ADO MoveNext( ) metaphor. The data array for the current row is stored in the fields property of the recordset object, $rs. MoveNext( ) offers the highest performance among all the techniques for iterating through a recordset:

$rs = $db->Execute("select * from emp where empno>:emp", array('emp' => 7900));
while (!$rs->EOF) {
print_r($rs->fields);
$rs->MoveNext();
}

And if you are interested in having the data returned in a 2-dimensional array, you can use:

$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));

Now to obtain only the first row as an array:

$arr = $db->GetRow("select * from emp where empno=:emp", array('emp' => 7900));

Or to retrieve only the first field of the first row:

$arr = $db->GetOne("select ename from emp where empno=:emp", array('emp' => 7900));

For easy pagination support, we provide the SelectLimit function. The following will perform a select query, limiting it to 100 rows, starting from row 201 (row 1 being the 1st row):

$offset = 200; $limitrows = 100;
$rs = $db->SelectLimit('select * from table', $limitrows, $offset);

The $offset parameter is optional.
Array Fetch Mode

When data is being returned in an array, you can choose the type of array the data is returned in.

1. Numeric indexes - use $connection->SetFetchMode(ADODB_FETCH_NUM).
2. Associative indexes - the keys of the array are the names of the fields (in upper-case). Use $connection->SetFetchMode(ADODB_FETCH_ASSOC).
3. Both numeric and associative indexes - use $connection->SetFetchMode(ADODB_FETCH_BOTH).

The default is ADODB_FETCH_BOTH for Oracle.
Caching

You can define a database cache directory using $ADODB_CACHE_DIR, and cache the results of frequently used queries that rarely change. This is particularly useful for SQL with complex where clauses and group-by's and order-by's. It is also good for relieving heavily-loaded database servers.

This example will cache the following select statement for 3600 seconds (1 hour):

$ADODB_CACHE_DIR = '/var/adodb/tmp';
$rs = $db->CacheExecute(3600, "select names from allcountries order by 1");

There are analogous CacheGetArray( ), CacheGetRow( ), CacheGetOne( ) and CacheSelectLimit( ) functions. The first parameter is the number of seconds to cache. You can also pass a bind array as a 3rd parameter (not shown above).

There is an alternative syntax for the caching functions. The first parameter is omitted, and you set the cacheSecs property of the connection object:

$ADODB_CACHE_DIR = '/var/adodb/tmp';
$connection->cacheSecs = 3600;
$rs = $connection->CacheExecute($sql, array('id' => 1));


3. Using Prepare( ) For Frequently Used Statements

Prepare( ) is for compiling frequently used SQL statement for reuse. For example, suppose we have a large array which needs to be inserted into an Oracle database. The following will result in a massive speedup in query execution (at least 20-40%), as the SQL statement only needs to be compiled once:

$stmt = $db->Prepare('insert into table (field1, field2) values (:f1, :f2)');
foreach ($arrayToInsert as $key => $value) {
$db->Execute($stmt, array('f1' => $key, 'f2' => $val);
}


4. Working With LOBs

Oracle treats data which is more than 4000 bytes in length specially. These are called Large Objects, or LOBs for short. Binary LOBs are BLOBs, and character LOBs are CLOBs. In most Oracle libraries, you need to do a lot of work to process LOBs, probably because Oracle designed it to work in systems with little memory. ADOdb tries to make things easy by assuming the LOB can fit into main memory.

ADOdb will transparently handle LOBs in select statements. The LOBs are automatically converted to PHP variables without any special coding.

For updating records with LOBs, the functions UpdateBlob( ) and UpdateClob( ) are provided. Here's a BLOB example. The parameters should be self-explanatory:

$ok = $db->Execute("insert into aTable (id, name, ablob)
values (aSequence.nextVal, 'Name', null)");
if (!$ok) return LogError($db->ErrorMsg());
# params: $tableName, $blobFieldName, $blobValue, $whereClause
$db->UpdateBlob('aTable', 'ablob', $blobValue, 'id=aSequence.currVal');

and the analogous CLOB example:

$ok = $db->Execute("insert into aTable (id, name, aclob)
values (aSequence.nextVal, 'Name', null)");
if (!$ok) return LogError($db->ErrorMsg());
$db->UpdateClob('aTable', 'aclob', $clobValue, 'id=aSequence.currVal');

Note that LogError( ) is a user-defined function, and not part of ADOdb.

Inserting LOBs is more complicated. Since ADOdb 4.55, we allow you to do this (assuming that the photo field is a BLOB, and we want to store $blob_data into this field, and the primary key is the id field):

$sql = "INSERT INTO photos ( ID, photo) ".
"VALUES ( :id, empty_blob() )".
" RETURNING photo INTO :xx";

$stmt = $db->PrepareSP($sql);
$db->InParameter($stmt, $id, 'id');
$blob = $db->InParameter($stmt, $blob_data, 'xx',-1, OCI_B_BLOB);
$db->StartTrans();
$ok = $db->Execute($stmt);
$db->CompleteTrans();

5. REF CURSORs

Oracle recordsets can be passed around as variables called REF Cursors. For example, in PL/SQL, we could define a function open_tab that returns a REF CURSOR in the first parameter:

TYPE TabType IS REF CURSOR RETURN TAB%ROWTYPE;

PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames IN VARCHAR) IS
BEGIN
OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames;
END open_tab;

In ADOdb, we could access this REF Cursor using the ExecuteCursor() function. The following will find all table names that begin with 'A' in the current schema:

$rs = $db->ExecuteCursor("BEGIN open_tab(:refc,'A%'); END;",'refc');
while ($arr = $rs->FetchRow()) print_r($arr);

The first parameter is the PL/SQL statement, and the second parameter is the name of the REF Cursor.


6. In and Out Parameters

The following PL/SQL stored procedure requires an input variable, and returns a result into an output variable:

PROCEDURE data_out(input IN VARCHAR, output OUT VARCHAR) IS
BEGIN
output := 'I love '||input;
END;

The following ADOdb code allows you to call the stored procedure:

$stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;");
$input = 'Sophia Loren';
$db->InParameter($stmt,$input,'a1');
$db->OutParameter($stmt,$output,'a2');
$ok = $db->Execute($stmt);
if ($ok) echo ($output == 'I love Sophia Loren') ? 'OK' : 'Failed';

PrepareSP( ) is a special function that knows about bind parameters. The main limitation currently is that IN OUT parameters do not work.
Bind Parameters and REF CURSORs

We could also rewrite the REF CURSOR example to use InParameter (requires ADOdb 4.53 or later):

$stmt = $db->PrepareSP("BEGIN adodb.open_tab(:refc,:tabname); END;");
$input = 'A%';
$db->InParameter($stmt,$input,'tabname');
$rs = $db->ExecuteCursor($stmt,'refc');
while ($arr = $rs->FetchRow()) print_r($arr);

Bind Parameters and LOBs

You can also operate on LOBs. In this example, we have IN and OUT parameters using CLOBs.

$text = 'test test test';
$sql = "declare rs clob; begin :rs := lobinout(:sa0); end;";
$stmt = $conn -> PrepareSP($sql);
$conn -> InParameter($stmt,$text,'sa0', -1, OCI_B_CLOB); # -1 means variable length
$rs = '';
$conn -> OutParameter($stmt,$rs,'rs', -1, OCI_B_CLOB);
$conn -> Execute($stmt);
echo "return = ".$rs."
";

Similarly, you can use the constant OCI_B_BLOB to indicate that you are using BLOBs.
Reusing Bind Parameters with CURSOR_SHARING=FORCE

Many web programmers do not care to use bind parameters, and prefer to enter the SQL directly. So instead of:

$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));

They prefer entering the values inside the SQL:

$arr = $db->GetArray("select * from emp where empno>7900");

This reduces Oracle performance because Oracle will reuse compiled SQL which is identical to previously compiled SQL. The above example with the values inside the SQL is unlikely to be reused. As an optimization, from Oracle 8.1 onwards, you can set the following session parameter after you login:

ALTER SESSION SET CURSOR_SHARING=FORCE

This will force Oracle to convert all such variables (eg. the 7900 value) into constant bind parameters, improving SQL reuse.

More speedup tips.


7. Dates and Datetime in ADOdb

There are two things you need to know about dates in ADOdb.

First, to ensure cross-database compability, ADOdb assumes that dates are returned in ISO format (YYYY-MM-DD H24:MI:SS).

Secondly, since Oracle treats dates and datetime as the same data type, we decided not to display the time in the default date format. So on login, ADOdb will set the NLS_DATE_FORMAT to 'YYYY-MM-DD'. If you prefer to show the date and time by default, do this:

$db = NewADOConnection('oci8');
$db->NLS_DATE_FORMAT = 'RRRR-MM-DD HH24:MI:SS';
$db->Connect($tns, $user, $pwd);

Or execute:

$sql = "ALTER SESSION SET NLS_DATE_FORMAT = 'RRRR-MM-DD HH24:MI:SS'";
$db->Execute($sql);

If you are not concerned about date portability and do not use ADOdb's portability layer, you can use your preferred date format instead.

8. Database Portability Layer

ADOdb provides the following functions for portably generating SQL functions as strings to be merged into your SQL statements:
Function Description
DBDate($date) Pass in a UNIX timestamp or ISO date and it will convert it to a date string formatted for INSERT/UPDATE
DBTimeStamp($date) Pass in a UNIX timestamp or ISO date and it will convert it to a timestamp string formatted for INSERT/UPDATE
SQLDate($date, $fmt) Portably generate a date formatted using $fmt mask, for use in SELECT statements.
OffsetDate($date, $ndays) Portably generate a $date offset by $ndays.
Concat($s1, $s2, ...) Portably concatenate strings. Alternatively, for mssql use mssqlpo driver, which allows || operator.
IfNull($fld, $replaceNull) Returns a string that is the equivalent of MySQL IFNULL or Oracle NVL.
Param($name) Generates bind placeholders, using ? or named conventions as appropriate.
$db->sysDate Property that holds the SQL function that returns today's date
$db->sysTimeStamp Property that holds the SQL function that returns the current timestamp (date+time).
$db->concat_operator Property that holds the concatenation operator
$db->length Property that holds the name of the SQL strlen function.
$db->upperCase Property that holds the name of the SQL strtoupper function.
$db->random Property that holds the SQL to generate a random number between 0.00 and 1.00.
$db->substr Property that holds the name of the SQL substring function.

ADOdb also provides multiple oracle oci8 drivers for different scenarios:
Driver Name Description
oci805 Specifically for Oracle 8.0.5. This driver has a slower SelectLimit( ).
oci8 The default high performance driver. The keys of associative arrays returned in a recordset are upper-case.
oci8po The portable Oracle driver. Slightly slower than oci8. This driver uses ? instead of :bindvar for binding variables, which is the standard for other databases. Also the keys of associative arrays are in lower-case like other databases.

Here's an example of calling the oci8po driver. Note that the bind variables use question-mark:

$db = NewADOConnection('oci8po');
$db->Connect($tns, $user, $pwd);
$db->Execute("insert into atable (f1, f2) values (?,?)", array(12, 'abc'));


9. Connecting to Oracle

Before you can use ADOdb, you need to have the Oracle client installed and setup the oci8 extension. This extension comes pre-compiled for Windows (but you still need to enable it in the php.ini file). For information on compiling the oci8 extension for PHP and Apache on Unix, there is an excellent guide at oracle.com.
Should You Use Persistent Connections

One question that is frequently asked is should you use persistent connections to Oracle. Persistent connections allow PHP to recycle existing connections, reusing them after the previous web pages have completed. Non-persistent connections close automatically after the web page has completed. Persistent connections are faster because the cost of reconnecting is expensive, but there is additional resource overhead. As an alternative, Oracle allows you to pool and reuse server processes; this is called Shared Server (also known as MTS).

The author's benchmarks suggest that using non-persistent connections and the Shared Server configuration offer the best performance. If Shared Server is not an option, only then consider using persistent connections.
Connection Examples

Just in case you are having problems connecting to Oracle, here are some examples:

a. PHP and Oracle reside on the same machine, use default SID, with non-persistent connections:

$conn = NewADOConnection('oci8');
$conn->Connect(false, 'scott', 'tiger');

b. TNS Name defined in tnsnames.ora (or ONAMES or HOSTNAMES), eg. 'myTNS', using persistent connections:

$conn = NewADOConnection('oci8');
$conn->PConnect(false, 'scott', 'tiger', 'myTNS');

or

$conn->PConnect('myTNS', 'scott', 'tiger');

c. Host Address and SID

$conn->connectSID = true;
$conn->Connect('192.168.0.1', 'scott', 'tiger', 'SID');

d. Host Address and Service Name

$conn->Connect('192.168.0.1', 'scott', 'tiger', 'servicename');

e. Oracle connection string:

$cstr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$host)(PORT=$port))
(CONNECT_DATA=(SID=$sid)))";
$conn->Connect($cstr, 'scott', 'tiger');

f. ADOdb data source names (dsn):

$dsn = 'oci8://user:pwd@tnsname/?persist'; # persist is optional
$conn = ADONewConnection($dsn); # no need for Connect/PConnect

$dsn = 'oci8://user:pwd@host/sid';
$conn = ADONewConnection($dsn);

$dsn = 'oci8://user:pwd@/'; # oracle on local machine
$conn = ADONewConnection($dsn);

With ADOdb data source names, you don't have to call Connect( ) or PConnect( ).


10. Error Checking

The examples in this article are easy to read but a bit simplistic because we ignore error-handling. Execute( ) and Connect( ) will return false on error. So a more realistic way to call Connect( ) and Execute( ) is:

function InvokeErrorHandler()
{
global $db; ## assume global
MyLogFunction($db->ErrorNo(), $db->ErrorMsg());
}
if (!$db->Connect($tns, $usr, $pwd)) InvokeErrorHandler();

$rs = $db->Execute("select * from emp where empno>:emp order by empno",
array('emp' => 7900));
if (!$rs) return InvokeErrorHandler();
while ($arr = $rs->FetchRow()) {
print_r($arr);
echo "
";
}

You can retrieve the error message and error number of the last SQL statement executed from ErrorMsg( ) and ErrorNo( ). You can also define a custom error handler function. ADOdb also supports throwing exceptions in PHP5.


Handling Large Recordsets (added 27 May 2005)
The oci8 driver does not support counting the number of records returned in a SELECT statement, so the function RecordCount() is emulated when the global variable $ADODB_COUNTRECS is set to true, which is the default. We emulate this by buffering all the records. This can take up large amounts of memory for big recordsets. Set $ADODB_COUNTRECS to false for the best performance.

This variable is checked every time a query is executed, so you can selectively choose which recordsets to count.

Friday, September 14, 2007

Cara Instalasi XAMPP

XAMPP merupakan sebuah paket instalasi untuk PHP, APACHE dan MySQL. Dengan menggunakan XAMPP, kita tidak perlu lagi repot menginstall ketiga software itu secara terpisah. XAMPP dapat di download di http://www.apachefriends.org/en/index.html. Berikut ini adalah cara menginstall XAMPP.

1. Jalankan file xampp-win32-1.4.12-installer.exe (atau versi lainnya)

2. Kemudian akan tampil pilihan untuk memilih bahasa ketika proses instalasi berjalan. Silakan pilih bahasa Indonesian atau English, kecuali anda menguasai bahasa lainnya. Pada contoh ini saya memilih bahasa Indonesian karena saya cinta bahasa Indonesia. Memilih bahasa

3. Proses instalasi akan dimulai. Klik Maju untuk memulainya. Mulai Instalasi


4. Akan muncul lisensi software. Silahkan membacanya jika anda mau, tetapi saya lebih suka untuk tidak membacanya karena terlalu banyak. Klik Saya Setuju untuk melanjutkan.Lisensi Software

5. Selanjutnya silakan anda pilih lokasi install untuk XAMPP. Kemudian klik install

6. Tunggu beberapa saat sampai proses instalasi selesai.Tunggu sebentar

7. Instalasi selesai

8. Sampai tahap ini, berarti kita sudah menginstal XAMPP. Itu berarti kita sudah selesai menginstall PHP, APACHE dan MYSQL. Langkah selanjutnya adalah menjalankan servicenya.

9. Jalankan XAMPP Control Panel yang ada di desktop. Atau anda juga dapat menjalankan XAMPP Control Panel dari menu Start -> All Programs -> apachefriends -> xampp -> xampp control panel. xampp control panel


10. Nyalakan Apache dan Mysql dengan mengklik tombol Start. Buka web browser anda, lalu ketikkan http://localhost. Jika tampilannya seperti di bawah ini, maka apache sudah terinstall dengan benar.


11. Sekedar informasi saja, document root milik XAMPP terletak pada folder E:\Program Files\apachefriends\xampp\htdocs. Hal ini disebabkan karena saya menginstall XAMPP pada folder E:\Program Files\apachefriends.

Thursday, September 13, 2007

PhpMyAdmin

Phpmyadmin adalah suatu aplikasi yang dibuat dengan bahasa pemrograman PHP yang ditujukan untuk pengelolaan basis data MySQL melalui Internet. Fungsi phpmyadmin sama dengan fungsi software lain seperti SQLYOG dan MySQLFront. Hanya saja PhpMyAdmin adalah free software. Sebelum mengikuti tutorial ini lebih lanjut, ada baiknya anda mendownload dulu phpmyadmin.

Cara Menggunakan Phpmyadmin

1. Pastikan Apache, PHP dan MySQL sudah terinstall di komputer Anda. Copy file phpMyAdmin-2.5.6.zip ke dalam folder di mana anda menyimpan file php (dalam Document Root)

2. Extract file tersebut sehingga akan terbentuk sebuah folder bernama phpMyAdmin-2.5.6

3. Bukalah web browser dan ketikkan http://localhost, lalu carilah folder tersebut.
Jika web browser anda menampilkan halaman sbb, maka anda harus mengatur / konfigurasi username dan password mysql di phpmyadmin terlebih dahulu.

4. Akan tetapi jika tampilannya sebagai berikut, berarti anda tidak perlu melakukan pengaturan / konfigurasi username dan password mysql di phpmyadmin

5. Jika tampilannya seperti pada gambar 3, maka anda harus melakukan konfigurasi username dan password mysqldi phpmyadmin. Caranya adalah buka folder phpMyAdmin-2.5.6 melalui windows explorer. Kemudian bukalah file config.inc.php (boleh menggunakan Dreamweaver maupun notepad).

6. Ubahlah beberapa settingan sbb :
di baris ke 69 : $cfg[’Servers’][$i][’host’] = ‘localhost’;
$cfg[’Servers’][$i][’host’] berisi host atau komputer tempat database mysql berada. Isi dengan localhost jika database mysql berada di komputer anda

Di baris ke-70 : $cfg[’Servers’][$i][’port’] = ‘’;
$cfg[’Servers’][$i][’port’] adalah port yang digunakan mysql. Kosongkan jika mysql anda menggunakan port standar (3306)

Di baris ke-83 : $cfg[’Servers’][$i][’user’] = ‘root’;
$cfg[’Servers’][$i][’user’] adalah user yang digunakan untuk koneksi ke mysql

Di baris ke-84 : $cfg[’Servers’][$i][’password’] = ‘’;
$cfg[’Servers’][$i][’password’] adalah password yang digunakan untuk koneksi ke mysql

Monday, August 20, 2007

Membuat Halaman Login Dengan PHP, MySQL, AJAX, Script.aculo.us dan Prototype.js (bag 2)

Oke, sekarang akan saya lanjutkan tutorial yang kedua. Saya anggap Anda sudah mendownload script.acyulo.us dan prototype.js. Kalo belum, silakan anda download lebih dahulu.
Silakan buka file login.php dan ubah menjadi sebagai berikut.
login.php


buat juga CSS nya dan simpan dengan nama style.css


sampai sejauh ini, kita udah membuat 2 buah file, yaitu login.php dan style.css, selanjutnya kita harus membuat satu file lagi yaitu ajax.php yang akan digunakan untuk mengecek login. Kita juga butuh sebuah database yang berisikan username dan password. Tunggu tutorial bagian ke-3 ya....

Thursday, August 16, 2007

Membuat Halaman Login Dengan PHP, MySQL, AJAX, Script.aculo.us dan Prototype.js (bag 1)

Dalam tutorial kali ini, saya akan menjelaskan bagaimana cara membuat halaman login dengan PHP, MySQL, AJAX, ScriptAculous dan Prototype.js. Untuk mengikuti tutorial ini, Anda sebaiknya sudah mengerti konsep webserver, PHP, dan database MySQL. Kalo belum, sebaiknya Anda mempelajarinya terlebih dahulu. Anda juga harus mengerti AJAX, ScriptAculous dan Prototype.js. Kalo belum mengerti, sebaiknya baca tutorialnya di sini dulu.

Oke, kita mulai saja ya... Pertama Anda harus menyiapkan sebuah halaman HTML untuk login. Kita beri nama "login.php".


saya rasa untuk tag HTML tidak perlu saya jelaskan lagi. Itu adalah tag HTML untuk membuat halaman login yang terdiri dari textbox username dan password. Dalam HTML di atas juga saya buatkan sebuah div untuk menampung hasil error ketika proses login berlangsung. Untuk mengikuti tutorial login bagian ke2, sebaiknya Anda download dulu library prototype.js dan scriptaculous. Tunggu tutorial bagian keduanya ya....

Sunday, July 22, 2007

How To Connect PHP - MySQL

In this post, I will explain you about PHP and MySQL. You can use PHP with MySQL database. You only need a simple script to connect PHP- MySQL.
1. mysql_connect() -- Open a connection to a MySQL Server
This function need several parameters. For example :
mysql_connect("localhost","root","12345")
notes : localhost --> the mysql server name
root --> the mysql username
12345 --> the mysql password

example : $link = mysql_connect("localhost", "mysql_user", "mysql_password")
or die("Could not connect");

2. mysql_select_db() --> Select a MySQL database
You need database name for this function
example : mysql_select_db("mysql")
notes : mysql is the database name is mysql database

3. mysql_query() --> Send a MySQL query
example : $result = mysql_query("SELECT * WHERE user='jhon'")
or die("Invalid query");
notes : SELECT * WHERE user='jhon' is query for mysql.

Monday, May 21, 2007

Date Function on PHP

to display the time and date in PHP, we can use date function. This function have several parameter. example

<?
date('d-m-y h:i:s')
?>
this syntax will return 21-05-2007 15:25:32.
For other parameters, please try to change the example above.
format character Description Example returned values
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
F A full textual representation of a month, such as January or March January through December
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
I (capital i) Whether or not the date is in daylights savings time 1 if Daylight Savings Time, 0 otherwise.
j Day of the month without leading zeros 1 to 31
l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
O Difference to Greenwich time (GMT) in hours Example: +0200
r RFC 822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
s Seconds, with leading zeros 00 through 59
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
t Number of days in the given month 28 through 31
T Timezone setting of this machine Examples: EST, MDT ...
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
W ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year)
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
z The day of the year 0 through 366
Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 43200