Kategori
PHP

Instant Sorting Function with PHP

Kategori
PHP

Code Igniter : Export Data into PDF File

Case Study : Data Export Mysql Database into a PDF file in Code Igniter.
Requirements:
1. Webserver package, already installed.
2. Code Igniter Bundle.
3. Cezpdf library –> download here

Sometimes, when we make an application, we will need to exported data into a pdf file (apart from the excel file), for example to create letters or reports. With a library cezpdf (by Wayne Munro), make a report as a pdf not be too difficult.

A. Preparing Database
1. Create a database with the name db_tutorial.
2. Create a table named tb_member, with the structure of the table below,

3. Insert a few sample data in tb_member, such as the data below,

4. Okay, done with the database.

B. Prepare files and directory structure
1. Install CodeIgniter, by extracting the bundle CI and place it in your document root.
2. Set the database settings (system-config-application-database.php) by setting the database to be used (db name: db_tutorial)
3. Set the url base config (system-config-application-config.php)
4. Put the files cezpdf.php and class.pdf.php (the downloaded library Cezpdf above) in a folder system-application-libraries
5. Put the files in the folder pdf_helper.pdf-helper-application system.
6. Ok: D

C. Make a model
1. Type the following script,
[sourcecode language=”php”]
<?php
class Member_model extends Model {
function Member_Model() {
parent::Model();
}
function alldata()
{
$this->db->select(‘*’);
$this->db->from(‘tb_member’);
$this->db->order_by(‘no’,’ASC’);
$getData = $this->db->get();
if($getData->num_rows() > 0)
return $getData->result_array();
else return null;
}
}
?>
[/sourcecode]
2. Save with the name of the folder system member_model.php-models-application

D. Make Controller
1. Type the following script,
[sourcecode language=”php”]
<?php
class Member_con extends Controller {
public function __construct() {
parent::__construct();
$this->load->model(‘member_model’);
$this->load->helper(‘url’);
}
public function index() {
$data[‘member’] = $this->member_model->alldata();
$this->load->view(‘member_view’, $data);
}

function topdf () {
$this->load->library(‘cezpdf’);
$this->load->helper(‘pdf’);
prep_pdf();
$data[‘member’]= $this->member_model->alldata();
$titlecolumn = array(
‘no’ => ‘no’,
‘name’ => ‘name’,
‘address’ => ‘address’
);
$this->cezpdf->ezTable($data[‘member’], $titlecolumn,’Member Data’);
$this->cezpdf->ezStream();
}
}
?>
[/sourcecode]
2. Save with the name of the folder system member_model.php-models-application

E. Create View
1. Type the following script,
[sourcecode language=”php”]
<h4>Member Data</h4>
<?php if(count($member) > 0) { ?>
<table border="1">
<tr>
<th>No</th>
<th>Name</th>
<th>Address</th>
</tr>
<?php
foreach($member as $rows) {
echo "<tr>";
echo "
<td>". $rows[‘no’]."</td>
<td>". $rows[‘name’] ."</td>
<td>". $rows[‘address’] ."</td>
"; } ?>
</table>
<?php } ?>
<br> <br>
<a href='<?php echo base_url(); ?>index.php/member_con/topdf’><span

style=’color:green;’>Export to Pdf</span></a>
[/sourcecode]
2. Save with the name of the folder system member_model.php-models-application

F. Testing code
1. Open http://localhost/ci_tutor/index.php/member_con. You will see the data that exists in tb_member like the picture below,

2. Click the link export to pdf to export data into pdf file.
3. So automatically your browser (or download manager) will download the pdf file.
4. Open the pdf files, you will see data from tb_member displayed in pdf file:) See the picture below.

Happy coding: D

Kategori
PHP

String Functions in the PHP

Discussion Board: Introduction to the various functions – the basic string functions (which are often used) in PHP and its possible use.
Kebutuhan : Webserver Package, already installed.

Text is one of the sources of unstructured data is greatest, because most of the information stored in the text, whether text in a variety of filetype (doc txt pdf etc) and web-text (html). Today more often performed research involving the text, and computer science that involves the text of which is the Natural Language Processing, Text (Web) Mining, or Information Retrieval.

Here are some of functions of a text (string) in PHP which will often be used if you are struggling with studies involving text processing.

1. Adding a slash (\) in the string -> addslashes.
[sourcecode language=”php”]
<?php
$text = "This is Anne’s book.";
echo addslashes($text);
?>
[/sourcecode]
Output :
This is Anne\’s book.

Why is this important? In text processing, it is often a sign of the quote (‘) will cause an error when done parsing of the text, especially when we use regular expressions.

2. Breaking the string with the string -> explode.
[sourcecode language=”php”]
<?php
$sentence = "My name is June";
$word = explode(" ", $sentence);
print_r($word);
?>
[/sourcecode]
Output :
Array
(
[0] => My
[1] => name
[2] => is
[3] => June
)

Explode will break up the text and divide it into an array, like the example above, $text in-explode with the string “” (space). This is the basis of tokenizing algorithm, namely breaking the sentence in the word – the word constituent. Tokenizing will often be used in text processing.

3. Combining an array of strings in one string -> implode.
[sourcecode language=”php”]
<?php
$arrayWord = array(‘This’, ‘is’, ‘a’, ‘sentence’);
$joinString = implode(" ", $arrayWord);
echo $joinString;
?>
[/sourcecode]
Output :
This is a sentence

Implode, as seen from the example above (example: arrays in the sample-implode / merged by using the string space), is the opposite of the function No. 2 (explode). Implode function has an alias, which is Join.

4. Provides MD5 value from string -> md5.
[sourcecode language=”php”]
<?php
$string = ‘password’;
$stringMd5 = md5($string);
echo $stringMd5;
?>
[/sourcecode]
Output :
5f4dcc3b5aa765d61d8327deb882cf99

MD5 is a hash function (cryptographic one-way) is quite well known and often used for security (although it’s a lot md5 decryptor). Md5 function like this will often be used when we build an application that requires authentication (eg to log into the system).

5. Removes HTML tags in the string -> strip_tags
[sourcecode language=”php”]
<?php
$text = ‘<b>June Susan</b> <i> June June</i>’;
echo strip_tags($text); echo ‘<br>’;
echo strip_tags($text, ‘<i>’); // Allow tag <i>
?>
[/sourcecode]
Output :
June Susan June June

Before we can process the text from the web (which is usually in the form of hypertext / html), then we must be “clean” tag – html tags that exist in the text. This is where the strip_tags function is useful. We can remove all tags, or allow certain tags to remain in the text (see examples).

6. Calculating the length of string -> strlen.
[sourcecode language=”php”]
<?php
$string = ‘I am a superman’;
echo strlen($string);
?>
[/sourcecode]
Output :
15

Strlen count the number of characters (length) of the string, spaces, and symbols – symbols that exist in the string will also be calculated in function strlen.

Happy coding, then! 😀

Kategori
PHP

Get the Data from Database with Codeigniter and Show it with JQuery UI Tab

Studi Kasus : Read data from the database, show it in the JQuery UI Tab with AJAX.
Kebutuhan : Webserver package already installed.
File Download: 1. CodeIgniter. 2. JQuery. 3. JQuery UI If you’ve never used this UI, just download a theme that already exist without the customized first. 4. Mic JQuery Template Plugin.
Special Skill : PHP. Codeigniter.

A. Prepare the Database
1. Create a database with the name db_tutorial.
2. Create a table named tb_book, with the structure of the table below,

3. Insert some sample data into tb_book.
4. Again create a table named tb_member, with the structure of the table below,…

5. Insert some sample dta into tb_member.
6. Okay, done with database.

B. Prepare job folders and files – the files needed.
1. Prepare a folder with the name ci_tutor in your document root.
2. CodeIgniter extract in the folder you just created (here user_guide file in my CI delete), and set its cover base_url config, as well as the configuration database in system-config-application-database.php
3. Create a table named cssjs, then put your jQuery file (download file 2) jQuery UI (the downloaded file 3: I choose the template flickr), and files Mic jQuery Plugin Template (file 4) into the folder cssjs.
4. Ci_tutor folder structure is like this,

5. The cssjs folder’s structure is like picture below,

C. Model
1. We will create a model that will take all the data available in tb_book and tb_member. Type the following script,

[sourcecode language=”php”]
<?php
class Book_model extends Model {

public function getBook() {
$query = $this->db->get( ‘tb_book’ );
if( $query->num_rows() > 0 ) {
return $query->result();
} else {
return array();
}
}

public function getMember() {
$query = $this->db->get( ‘tb_member’ );
if( $query->num_rows() > 0 ) {
return $query->result();
} else {
return array();
}
}
}
?>
[/sourcecode]

2. Save with the name book_model.php save into system-application-models.

D. Controller
1. Type the following script,

[sourcecode language=”php”]
<?php
class Book_con extends Controller {
public function __construct() {
parent::__construct();
$this->load->model(‘book_model’);
}
public function index() {
$this->load->view(‘book_view’);
}
public function readBook() {
echo json_encode( $this->book_model->getBook() );
}
public function readMember() {
echo json_encode( $this->book_model->getMember() );
}
}
?>
[/sourcecode]

2. Save with the name book_con.php save into system-application-controllers.

E. View
1. Type the following script,

[sourcecode language=”php”]
<html>
<head>
<title>ITX.WEB.ID</title>
<base href="<?php echo base_url(); ?>" />
<link type="text/css" rel="stylesheet" href="cssjs/flick/jquery-ui-1.8.2.custom.css" />
<link type="text/css" rel="stylesheet" href="cssjs/styles.css" />
</head>
<body>
<center><h2> Book & Member List</h2></center>
<div id="tabs">

<ul>
<li><a href="#read">Book List</a></li>
<li><a href="#read2">Member List</a></li>
</ul>

<div id="read">
<table id="tabel"></table>
</div>

<div id="read2">
<table id="tabel2"></table>
</div>

</div>

<script type="text/javascript" src="cssjs/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="cssjs/jquery-ui-1.8.2.min.js"></script>
<script type="text/javascript" src="cssjs/jquery-templ.js"></script>

<script type="text/template" id="readTemp">
<tr>
<td>${id}</td>
<td>${title}</td>
<td>${author}</td>
</tr>

</script>

<script type="text/template" id="readTemp2">
<tr>
<td>${no}</td>
<td>${name}</td>
<td>${address}</td>
</tr>

</script>

<script type="text/javascript" src="cssjs/all.js"></script>
</body>
</html>
[/sourcecode]

2. Save with the name book_view.php save into system-application-views.

F. Create Javascript file that will read table records from sever with Ajax.
1. Type the following script,

[sourcecode language=”javascript”]
$( function() {
$( ‘#tabs’ ).tabs({
fx: { height: ‘toggle’, opacity: ‘toggle’ }
});

$.ajax({
url: ‘index.php/book_con/readBook’,
dataType: ‘json’,
success: function( response ) {
$( ‘#readTemp’ ).render( response ).appendTo( "#tabel" );
}
});

$.ajax({
url: ‘index.php/book_con/readMember’,
dataType: ‘json’,
success: function( response ) {
$( ‘#readTemp2’ ).render( response ).appendTo( "#tabel2" );
}
});

});
[/sourcecode]

2. Save with the name all.js and save into cssjs folder.

G. Arrange the view
1. Type the following script and save with the name style.css

[sourcecode language=”css”]
body {
font-family: Arial, Helvetica, sans-serif;
}

#tabs {
font-size: .9em;
margin: 0 auto;
width: 800px;
}

.ui-widget-content {
font-size: .8em;
}

#tabel, #tabel2 {
font-size: 1.3em;
width: 100%;
}

#tabel tr:nth-child(2n) {
background: #EAEAEA;
}

#tabel tr:hover {
background: #CCCCCC;
}

#tabel td {
padding: 6px;
margin: 8px;
}
[/sourcecode]

H. Testing code
1. Go to the browser, and run http://localhost/ci_tutor/index.php/book_con/
2. If successful, you will see picture below.

3. Click on the Member List tab, so it will display member data from tb_member.

4. Be creative with another Jquery UI 😀

Happy coding 😀

Kategori
PHP

Round Number in PHP

Discussion Board : One of the important functions in the mathematical calculations, that do rounding numbers with PHP
Requirements : Webserver package, already installed.

One friend who is building an ecommerce never ask something like this: “How can I create a program that, items weighing less than 1 kg to 1 kg is considered 1 kg, then more than 1 kg to 2 kg is considered 2 kg, and so on? “
The problem above can be written as follows:
1> = weight> 0 —> considered to be 1 kg
2> weight => 1 —> 2 kg is considered
etc. ..

Actually, this problem is not a complex problem. Absolutely not complicated in fact. Examples of the above case is just one example of cases that can be resolved easily by Rounding. In PHP, the known three mathematical functions that can be used for rounding, namely ceil, Floor, and Round.

1. Rounding upwards (ceil).
For example for the above case

[sourcecode language=”php”]
<?php
$berat1 = 0.5;
$berat2 = 1.5;
$berat3 = 2;
echo ‘berat 1 =’.ceil($berat1); echo ‘<br />’;
echo ‘berat 2 =’.ceil($berat2); echo ‘<br />’;
echo ‘berat 3 =’.ceil($berat3);
?>
[/sourcecode]

If the script above is executed, then the output is as follows,
berat 1 = 1
berat 2 = 2
berat 3 = 2
So the conclusion is that the PHP function ceil will perform rounding upwards on the given number. This function will produce the nearest integer value of upwards of a number.

2. Rounding down (floor).
Floor used for rounding down. See the example below,

[sourcecode language=”php”]
<?php
$berat1 = 0.5;
$berat2 = 1.5;
$berat3 = 2;
echo ‘berat 1 =’.floor($berat1); echo ‘<br />’;
echo ‘berat 2 =’.floor($berat2); echo ‘<br />’;
echo ‘berat 3 =’.floor($berat3);
?>
[/sourcecode]

If the script above is executed, then the output is as follows,
berat 1 = 0
berat 2 = 1
berat 3 = 2
Contrary to ceil, the floor will do the rounding to the nearest integer value down of a number.

3. Rounding to the nearest
ROUND round a number to the nearest value in accordance with the number behind the comma deciman desired. For example,

[sourcecode language=”php”]
<?php
$berat1 = 0.58989;
$berat2 = 1.6;
$berat3 = 2.4;
echo ‘berat 1 =’.round($berat1, 2); echo ‘<br />’; // with 2 decimal
echo ‘berat 2 =’.round($berat2, 0); echo ‘<br />’; // 0 decimal
echo ‘berat 3 =’.round($berat3); // without parameter, so it will rounded in to the nearest integer
?>
[/sourcecode]

If the script above is executed, then the output is as follows,
berat 1 = 0.59
berat 2 = 2
berat 3 = 2

Hope it hels! 😀 Happy coding 😀

Kategori
PHP

Efficient Code using PHP Include

Discussion Board : Using PHP Include code to make listings more efficiently.
Requirements: Webserver Package, already installed.

INCLUDE, generally used for the php code that will be frequently used, means that the code which will often be written repeatedly in building applications or any coding in PHP.

Why using Include ?
1. It would be very inefficient if we must write the same code repeatedly.
2. If it were the case there are parts of the code that must be changed, then, once again, be very inefficient if you need to change the wrong one by one.

And once again, this will be very redundant and time-consuming and lead to potential human error. By using include, the problem – this problem can be overcome.

Does it Include?
PHP file include is inserted in another PHP file, generally include contain information that will repeatedly be used in other code. For example, if you want to build the site navigation to be displayed in every page of your site, then you simply write the code navigation is in one file for later to include it in every page of the site.

Case Studies : Using Include for Header and Footer.

1. Create a header.
Suppose we want to display today’s date as a header. Type the following script.

[sourcecode language=”php”]
<?php
echo "This is a HEADER, And ";
echo "Today is ";
echo date("F d");
echo ", ";
echo date("Y");
?>
[/sourcecode]

Code date The above will display today’s date. Save the script above with the name of header.php.

2. Creating a footer.
For example we will display the copyright as a footer to our site. Type the script below.

[sourcecode language=”php”]
<?php
echo "Copyright by itx.web.id";
?>
[/sourcecode]

Save the script above with the name footer.php

3. Placing the header and footer in the page.
Type the following script.

[sourcecode language=”php”]
<?php
include "header.php";
echo "<h1> This is the BODY of site !</h1>";
include "footer.php";
?>
[/sourcecode]

Suppose we want to put the header at the top page, then the code to header.php must diinclude weight on the code as well (on body). Similarly for the footers, because it is located at the bottom of the page, then the code is also placed at the bottom footer.php code.

4. The result?
Run body.php, it will display the picture as follows.

p.s. OHYA, save ALL the php file in the one – same folder. Ok, haapy cooding yah 😀

Kategori
PHP

Passing variables between pages in PHP with URL and Session

Case Studies : Passing variables between pages in PHP with PHP Session.
Needs : Webserver package, already installed .

For the case this time, assume that you will make the application logged on to the page – next page after the user is logged in, you want to continue to greet the user. Of course, you must store the variable name of the user right? Basically, there are four ways to do this, namely:
1. Pass the variable in the URL.
2. Through Session.
3. Via Cookie and,
4. With HTML Form.

This tutorial will discuss about the point to one and two of the four ways above, ie pass the variable through a combination of URL and Session.

1. Type the following script (named script1.php).

[sourcecode language=”php”]
<?php
session_start();
$_SESSION[‘username’] = "June";
?>
<html>
<head>
<TITLE>Just A Sample – ITX.WEB.ID</TITLE>
</head>
<body>
<?php
$mybook = "My Name is June";
echo "<a href=’mybook.php?book=$mybook’>";
echo "Click here to see your book!";
echo "</a>";
?>
</body>
</html>
[/sourcecode]

Note that in the script above, we assign a username variable manually (assumption: that the user has been logged and the username is saved in the session). So, how to store value in session is with the following syntax:
$_SESSION['username'] = "June";

Meanwhile, variable book will be passed through the URL. Its syntax is as follows:
mybook.php? book = $mybook , with variable mybook has been assigned previously.

Once executed, the script above will output the following :
Click here to see your book!

2. Type the following script (save it as mybook.php). The following script is the script from the script output link 1 above. This script will read a variable that has dilewat through URL and Session.

[sourcecode language=”php”]
<?php
session_start();
echo "<h2> Welcome to your Book, ";
echo $_SESSION[‘username’];
echo "! </h2> <br>";
echo "Your favorite book is ";
echo $_REQUEST[‘book’];
echo "<br>";
?>
[/sourcecode]

Note the section above. From script1.php, we know that we have missed 2 variables, namely variable book and variable username , with each – each value is My Name is June for variable book , and June for the variable username.

Then I read the second variable is:
1. Reading the variable book (which is passed via the URL): $_REQUEST ['book'] .
2. Reading the variable username (which is passed via Session): $_SESSION ['username'] .

Click the link generated script1.php, then you will be redirected to the script page 2 (mybook.php), with a view like the picture below.

Haaaapy Coding 😀

Kategori
PHP

Regular Expression ( Regex ) with PHP

Discussion Board : Introduction to the basic concept of Regular Expression syntax in PHP, with the sample few case for using PHP Regex.
Requirement : webserver package, already installed (or just PHP with Apache).

Regex? What it is?
Regular Expression (Regex) is a concept of pattern matching (pattern matching ) within a string. In general, the regular expression used for validation (in an information system development), or used for text processing (text processing). However, sometimes regular expression also often used in Information Retrieval.

Tutorial – tutorial below will mengkover cases – cases that can be handled with Regex, for example by using the Regex pattern matching.

1. What is the pattern “instant noodle” in a string?

[sourcecode language=”php”]
$string = ‘iloveindomieverymuch’;

$isMatch = preg_match("/indomie/", $string); //here the regex

echo $isMatch;
[/sourcecode]

Script above will produce output “1” because the “indomie” pattern exist in the “iloveindomieverymuch” string.diatas akan menghasilkan output “1” karena pattern “indomie” ada dalam string “iloveindomieverymuch”. As we can see, that preg_match will produce boolean value 1 if there is string match, and 0 if not.

2. Apakah string dimulai dengan pattern “ilove” ?
For checking the begin of string, use ^ symbol.

[sourcecode language=”php”]
<?php
$string = ‘iloveindomieverymuch’;
isMatch = preg_match("/^ilove/", $string)

if($isMatch) {
echo ‘The string begins with ilove’; //if there’s a match
}
else {
echo ‘The string does not begin with ilove’; //if there isn’t match
}
?>
[/sourcecode]

This Script above will produce output like below,
The string begins with ilove

3. Does the string end with a pattern “much”?
$ pattern can be used, or perhaps better with as below.

[sourcecode language=”php”]
<?php
$string = ‘iloveindomieverymuchactually’;
isMatch = preg_match("/much\z/i", $string)

if($isMatch) {
echo ‘The string ends with much’; //if there’s a match
}
else {
echo ‘The string does not end with much’; //if there isn’t match
}
?>
[/sourcecode]

When executed, the script above will output as follows,
The string does not end with much

This is because preg_match give value 0, because the string does not meet the rules specified by regex.

4. Strings, including letters or numbers?
The script below will check whether a word including the number (number), or composed of letters (name).

[sourcecode language=”php”]
<?php
$word= ‘ALAN’;
if(preg_match("/^[A-Z]/", $word)) {
$type = ‘name’;
}
else if(preg_match("/^[0-9]/", $word)) {
$type = ‘number’;
}
echo $type;
?>
[/sourcecode]

The output that may result from the script above is as follows,
name

However, if we replace $ word above with the string “1231”, it will produce output,
number

The above tutorial only gives examples of doing a regular expression with preg_match. Of course there are others, in PHP itself to the use of regular expression can be used with functions – functions such as preg_match_all, ereg, eregi, ereg_replace, preg_replace.
… and others.

For thecheatsheet of PHP regular expression, you can go here.

Ok, Happy Coding 😀

Kategori
PHP

Object Oriented Programming with PHP

Discussion Board : Introduction to object oriented programming concept on the PHP, especially class and inheritance.
Requirements: webserver package, already installed.

According Wikipedia.Com, Object Oriented Programming is paradigm to object-oriented programming. All data and functions within this paradigm is wrapped in a class or object.

Key in OOP is the object. Objects can be said as a collection of variables and functions (which in OOP, the variable referred to as properties, and functions called methods) that are collected in a single entity. Methods used to manipulate data in the object, the properties are part containing information about the data.

For this tutorial we will discuss two basic concepts in OOP, namely Class , and Inheritance .

Class.
Class is a representation of the object, inside the class methods and properties have . Immediately, we create a class (save with the name student.class.php , and put all the scripts in this tutorial in a folder at the same ).

[sourcecode language=”php”]
<?php
class student {

public $name;
public $address;

/*constructor, is a function that will always be executed when an object diinstansiasi / created. If a class must perform a certain function before running the code, then this is where to put that particular function (usually to call the library). */

public function __construct(){
echo ‘Student’s Data.<br />’;
}

public function show_name {
echo ‘Student’s name is : ‘.$this->name.'<br/>’;
}

public function show_address {
echo ‘Student’s address is : ‘.$this->address.'<br/>’;
}

}
?>
[/sourcecode]

Yup, you have created a class. For using that class, we need to create, or initialize an object from that class. Now, let’s try to make an object from Student class above.

[sourcecode language=”php”]
<?php
$student1 = new student; //this create new object in the class student named object student1

//assigning data into properties
$student1->name = ‘Alan’;
$student1->address = ‘Temari Street, 15’;

//call the method
$student1->show_name();
$student1->show_address();

?>
[/sourcecode]

That above script will produce something like this one,

Student’s Data
Student’s name is : Alan
Student’s address is : Temari Street, 15

Inheritance.
Inheritance is a capability for extending some class that will inherit ALL the parent class’s character. In this case, the class that will inherit is called child class.

[sourcecode language=”php”]
<?php
include(‘student.class.php’);

class newstudent extends student {
privat $register_number;

public function show_register_number () {
echo ‘Student’s Register Number is : ‘.$this->register_number.'<br/>’;
}

}
?>
[/sourcecode]

Can be explained that the object of new students (new student) must have different properties with the object pupil (student), where for the new students have a property register_number (registration number) that is not owned by the object pupil. Meanwhile, a new student object has all the characteristics possessed by the object pupil. This is where the concept of Inheritance useful. Instead of having to create a new class for new students object, we could extend it from an existing object, that object of students, by adding properties and methods specific to the new student object.

In this case,
object student (murid) –> parent class
object newstudent (murid baru) –> child class

For using child class, you can try to use this script below,

[sourcecode language=”php”]
<?php
$student2 = new newstudent; //this create new object in the class student named object student1

//assigning data into properties
$student2->name = ‘June’;
$student2->address = ‘Kebangkitan Street, 28’;
$student2->register_number = ‘193-123-111’;

//call the method
$student1->show_name();
$student1->show_register_number();
?>
[/sourcecode]

That above script will produce something like this one,

Student’s Data
Student’s name is : June
Student’s address is : Kebangkitan Street, 28
Student’s register number is : 193-123-111

The Ends 😀 Hope that tutorial above could give basic concept for Object oriented programming with PHP, however, this tutorial -surely- still very poor for those who want to learn OOP.

Happy Coding 😀

Kategori
PHP

Count TextArea Character in the Form with PHP

Case Study : Create script to count the character in the textarea
Requirements: WebServer Package, already installed.

Maybe we have ever find sms web application, ie applications that are used to send sms via web applications. Here we will not discuss about the processing of SMS, but we will discuss about the interface that is used in sending sms, usually in the form textarea, which will provide certain limitations on number of characters that have been determined (on sms, generally is 160 characters)

Nah. How do we calculate the characters written in the textarea?

With Javascript.

Step 1 : Prepare the work directory

  1. Create folder named tutorphp in your document root
  2. Save all file in this tutorial in this folder.

Step 2 :Create Form Textarea

  1. Type the following script,
    [sourcecode language=”php”]
    <html><head>
    <title>Itx.Web.Id</title>
    <script type="text/javascript" src="cek_karakter.js"></script>
    </head>
    <body>
    <form name=form method=post>
    <h3> Write Your Message Here </h3>
    <textarea onKeyPress=cek_karakter(this.form); onKeyDown=cek_karakter(this.form); name=teks rows=4 cols=30></textarea>
    <br> <br>
    <input size=1 value=10 name=total>
    </form>
    </body>

    </html>
    [/sourcecode]

  2. Save with the name hitung_textarea.php

Step 3 : Create Javascript to Count Character in the Textarea

  1. Type the following script,
    [sourcecode language=”javascript”]
    function cek_karakter(form) {
    maks = 10; // max character
    if (form.teks.value.length >= maks) {
    var message = "0 Character Left ! "; //alert if character limit reacher
    alert(message);
    form.teks.value = form.teks.value.substring(0, maks); //trim the textarea
    }
    else {
    form.total.value = maks – form.teks.value.length;} //count the character
    }
    [/sourcecode]
  2. Save with the name cek_karakter.js


Step 4 : Testing Code

  1. Go to http://localhost/tutorial/hitung_karakter.php. You’ll see a form that you created, with the character limit is 10 (you can set yourself)
  2. Try typing something in the textarea, then the counter will start counting down, and when the character limit has been reached, the alerts appear as shown below