Showing posts with label mysql. Show all posts
Showing posts with label mysql. Show all posts

The Oracle JDeveloper IDE

Java developers can choose among several different IDEs. (Integrated Development Environment)
  • Eclipse
  • Netbeans
  • JDeveloper
  • JCreator
  • IntelliJIDEA
Eclipse and Netbeans are open source software. Each IDE has it's strengths and weaknesses. There is IBM behind Eclipse, Sun behind Netbeans and Oracle behind JDeveloper. In this article we will examine JDeveloper. The JDeveloper enables you to develop Java enterprise applications as well as desktop applications. There are two things that I love about JDeveloper. It is it's look and feel. It is the best looking IDE. It is written in Swing toolkit. Looks exactly the same on both Windows and Linux. It is slower than Eclipse, but it is quite swift. At least for my test development. (I have not used it extensively.) The other thing that I like is that it comes in three different editions. The studio edition, the j2ee edition and the java edition. The basic java edition contains only the core Java and XML features. This was exactly what I needed. Why install features you will never use? The size of the download is smaller (currently 55 MB) and the application is more responsive.

Installation

First we download the JDeveloper IDE from the official download page. We must go through registration process to access the download file. It is a bit annoying. Especially, when you want to uprade your version and you have forgotten your password or login. (or both). I am lost in all those logins and passwords. At home, at work, on the web. The current version is 10.1.3.2. It was realesed in January 2007. I have downloaded the basic java edition. It is perfect for my development of small desktop applications in Java and Swing. There are also three install types. Windows, Mac and universal base install. I work on linux, so I have chosen the base install. It works on all platforms. The other two are probably optimized for those two plaforms. I assume. The dowload file name is jdevjavabase10132.zip.
We unzip the file to our preferred directory. Let's say ~/jdeveloper. Now we can lauch the JDeveloper IDE. The startup file is in the ~/jdeveloper/jdev/bin directory.
./jdev
When we first launch the JDeveloper, it will ask for the path to the Java jdk directory.
Type the full pathname of a J2SE installation (or Ctrl-C to quit), the path will be stored in ~/.jdev_jdk
On my system it is /home/vronskij/bin/jdk1.6.0_01. The path will be stored in the hidden .jdev_jdk file name located in the home directory. Then we should see this splashscreen.

JDeveloper splashscreen
Whoops. A dialog window pops up.


The problem is that I have the newest Java jdk1.6. And the JDeveloper is certified to run on the previous one. I have never encountered any problems regarding this issue. And there is a certain progress from the previous version of JDeveloper. We can grab the dialog box from behind the splashscreen. And click the skip message option.
Now we have been rewarded for our patience and hard work and we have the JDeveloper in full beauty. Ok. One more step. Close the Tip of the day dialog box. And do not forget to unclick the Show tips on startup box. Here we have a screenshot of our beautiful Oracle JDeveloper IDE version 10.1.3.2.0.

The Oracle JDeveloper screenshot
Oracle JDeveloper IDE

Creating a Swing application

I like this JDeveloper slim release, because the creation process is quite simple. (On the other hand, it could be even simpler.) Comparing to other IDE's it is. We do not have to go through all those enterprise apps, beans, libs and the like. We go to File menu, click New. Then we select Application. We give an application a name. In the next dialog window, we provide a name for a project that will host our application. We then go to the System Navigator. Select the project. Right click on the project name, select New Class. We are ready to start coding our Java Swing application.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class Puzzle extends JFrame implements ActionListener {

private JPanel centerPanel;
private JButton button;
private JLabel label;
private Image source;
private Image image;
int[][] pos;

public Puzzle() {

pos = new int[][] {
{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{9, 10, 11}
};


centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(4, 4, 0, 0));

ImageIcon sid = new ImageIcon(Puzzle.class.getResource("icesid.jpg"));
source = sid.getImage();


add(Box.createRigidArea(new Dimension(0, 5)), BorderLayout.NORTH);
add(centerPanel, BorderLayout.CENTER);


for ( int i = 0; i < 4; i++) {

for ( int j = 0; j < 3; j++) {

if ( j == 2 && i == 3) {
label = new JLabel("");
centerPanel.add(label);

} else {

button = new JButton();
button.addActionListener(this);
centerPanel.add(button);
image = createImage(new FilteredImageSource(source.getSource(),
new CropImageFilter(j*103, i*60, 103, 60)));
button.setIcon(new ImageIcon(image));
}
}
}

setSize(325, 275);
setTitle("Puzzle");
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}


public static void main(String[] args) {

new Puzzle();

}

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
Dimension size = button.getSize();

int labelX = label.getX();
int labelY = label.getY();
int buttonX = button.getX();
int buttonY = button.getY();
int buttonPosX = buttonX / size.width;
int buttonPosY = buttonY / size.height;
int buttonIndex = pos[buttonPosY][buttonPosX];



if (labelX == buttonX && (labelY - buttonY) == size.height ) {

int labelIndex = buttonIndex + 3;

centerPanel.remove(buttonIndex);
centerPanel.add(label, buttonIndex);
centerPanel.add(button,labelIndex);
centerPanel.validate();
}

if (labelX == buttonX && (labelY - buttonY) == -size.height ) {

int labelIndex = buttonIndex - 3;
centerPanel.remove(labelIndex);
centerPanel.add(button,labelIndex);
centerPanel.add(label, buttonIndex);
centerPanel.validate();
}

if (labelY == buttonY && (labelX - buttonX) == size.width ) {

int labelIndex = buttonIndex + 1;

centerPanel.remove(buttonIndex);
centerPanel.add(label, buttonIndex);
centerPanel.add(button,labelIndex);
centerPanel.validate();
}

if (labelY == buttonY && (labelX - buttonX) == -size.width ) {

int labelIndex = buttonIndex - 1;

centerPanel.remove(buttonIndex);
centerPanel.add(label, labelIndex);
centerPanel.add(button,labelIndex);
centerPanel.validate();
}
}
}
We have used a 308 x 238px image of Sid. Sid is one of the main characters in the Ice Age movie.
Continue Reading

PHP Operators Tutorial

In this part of the PHP programming tutorial, we will talk about operators.
An operator is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data.
We have several types of operators:
  • Arithmetic operators
  • Boolean operators
  • Relational operators
  • Bitwise operators
An operator may have one or two operands. An operand is one of the inputs (arguments) of an operator. Those operators that work with only one operand are called unary operators. Those who work with two operands are called binary operators.
+ and - signs can be addition and subtraction operators as well as unary sign operators. It depends on the situation.
php > print +2;
2
php > print -2;
-2
php > print 2;
2
php > print 2+2;
4
php > print 2-2;
0
The plus sign can be used to indicate that we have a positive number. But it is mostly not used. The minus sign changes the sign of a value.
php > $a = 1;
php > print -$a;
-1
php > print -(-$a);
1
Multiplication and addition operators are examples of binary operators. They are used with two operands.
php > print 3 * 3;
9
php > print 3 + 3;
6

The assignment operator

The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In PHP, a variable begins with a $ character. In mathematics, the = operator has a different meaning. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.
php > $x = 1;
php > print $x;
1
Here we assign a number to an $x variable.
php > $x = $x + 1;
php > print $x;
2
The previous expression does not make sense in mathematics. But it is legal in programming. The expression means that we add 1 to the $x variable. The right side is equal to 2 and 2 is assigned to x.
php > 3 = $x;

Parse error: syntax error, unexpected '=' in php shell code on line 1
This code example results in syntax error. We cannot assign a value to a literal.

Arithmetic operators

The following is a table of arithmetic operators in PHP.
SymbolName
+Addition
-Subtraction
*Multiplication
/Division
%Modulo
The following example shows arithmetic operations.
<?php

$a = 10;
$b = 11;
$c = 12;

$add = $a + $b +$c;
$sub = $c - $a;
$mult = $a * $b;
$div = $c / 3;


echo $add, " " , $sub, " ";
echo $mult," ", $div, " ";
echo "\n";

?>
All these are known operators from mathematics.
$ php arithmetic.php 
33 2 110 4
php > print 9 % 4;
1
The % operator is called the modulo operator. It finds the remainder of division of one number by another. 9 % 4, 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1.

Concatenating strings

We use the dot . operator to concatenate strings.
php > print 'return' . 'of' . 'the' . 'king';
returnoftheking
The dot operator makes one string from four pieces of strings.
php > print 3 . 'apples';
3apples
We can concatenate strings with numbers with the dot operator. Internally, the number is converted to a string a the two strings are concatenated in the end.
php > print 'apples' * 3;
0
php > print 'apples' - 'oranges';
0
php > print 'apples' + 'oranges';
0
Using other operators with strings does not make much sense. We get zero.
php > print (Integer) 'apple';
0
This is because in a numerical context, a string is equal to zero.

Boolean operators

In PHP, we have and, or and negation ! boolean operators. With boolean operators we perform logical operations. These are often used with if and while keywords.
<?php

$a = (True and True);
$b = (True and False);
$c = (False and True);
$d = (False and False);

var_dump($a, $b, $c, $d);

?>
This example shows the logical and operator. The logical and operator evaluates to True only if both operands are True.
$ php andop.php 
bool(true)
bool(false)
bool(false)
bool(false)
The logical or operator evaluates to True, if either of the operands is True.
<?php

$a = (True or True);
$b = (True or False);
$c = (False or True);
$d = (False or False);

var_dump($a, $b, $c, $d);

?>
If one of the sides of the operator is True, the outcome of the operation is True.
$ php orop.php 
bool(true)
bool(true)
bool(true)
bool(false)
The negation operator ! makes True False and False True.
<?php

$a = ! False;
$b = ! True;
$c = ! (4<3);

var_dump($a, $b, $c);

?>
The example shows the negation operator in action.
$ php negation.php 
bool(true)
bool(false)
bool(true)
And, or operators are short circuit evaluated. Short circuit evaluation means that the second argument is only evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of and evaluates to false, the overall value must be false; and when the first argument of or evaluates to true, the overall value must be true. (wikipedia)
A typical example follows.
<?php

$x = 10;
$y = 0;

if ($y != 0 and x/y < 100) {
echo "a small value";
}

?>
The first part of the expression evaluates to False. The second part of the expression is not evaluated. Otherwise, we would get a Division by zero error.

Relational Operators

Relational operators are used to compare values. These operators always result in boolean value.
SymbolMeaning
<strictly less than
<=less than or equal to
>greater than
>=greater than or equal to
==equal to
!= or <>not equal to
===identical
!==not identical
php > var_dump(3 < 4);
bool(true)
php > var_dump(3 == 4);
bool(false)
php > var_dump(4 >= 3);
bool(true)
As we already mentioned, the relational operators return boolean values.
Notice that the relational operators are not limited to numbers. We can use them for other objects as well. Although they might not always be meaningful.
php > var_dump("six" == "six");
bool(true)
php > var_dump("a" > 6);
bool(false)
php > var_dump('a' < 'b');
bool(true)
We can compare string objects too. We can use relational operators for different object types. In our case we compare a string with a number.
php > var_dump('a' < 'b');
What exactly happens here? Computers do not know characters or strings. For them, everything is just a number. Characters are special numbers stored in specific tables. Like ASCII.
<?php

echo 'a' < 'b';
echo "\n";

echo 'a is:', ord('a');
echo "\n";
echo 'b is:', ord('b');
echo "\n";

?>
Internally, the a and b characters are numbers. So when we compare two characters, we compare their stored numbers. The built-in ord() function returns the ASCII value of a single character.
$ php compare.php 
1
a is:97
b is:98
In fact, we compare two numbers. 97 with 98.
php > print "ab" > "aa";
1
Say we have a string with more characters. If the first characters are equal, we compare the next ones. In our case, the b character at the second position has a greater value than the a character. That is why "ab" string is greater than "aa" string. Comparing strings in such a way does not make much sense, of course. But it is technically possible.

Assignment, equality and identity

As you might notice, there are one sign operator (=), two signs operator (==) and three signs (===) operator. Now we will talk about the differences among these operators.
The one sign (=) operator is the assignment operator. It loads a value to a variable.
php > $a = 6;
php > echo $a;
6
In the example, we assign a value 6 to the $a variable. $a now contains number six. We can show the contents of the $a variable by using the echo command.
The two signs (==) operator is the loose equality operator. It is used to test if the values in question are equal. Note, that PHP interpreter does some implicit casting when this operator is used. This leads to some non intuitive results.
php > var_dump(false == 0);
bool(true)
php > var_dump(false == array());
bool(true)
php > var_dump(true == 1);
bool(true)
php > var_dump(true == "string");
bool(true)
php > var_dump(117 == "000117");
bool(true)
For many programmers, beginners or programmers coming from other languages, these results might be surprising. If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
The three sign (===) operator is the strict comparison operator. It is called the identity operator. This operator returns true only if the values of the operands are equal and are of the same type.
php > var_dump(false === 0);
bool(false)
php > var_dump(false === array());
bool(false)
php > var_dump(true === 1);
bool(false)
php > var_dump(true === "string");
bool(false)
php > var_dump(117 === "000117");
bool(false)
As we can see, the identity operator returns the opposite results. This operator is more intuitive and more safe to use.

Bitwise operators

Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal or hexadecimal symbols are only notations of the same number. Bitwise operators work with bits of a binary number. We have binary logical operators and shift operators. Bitwise operators are seldom used in higher level languages like PHP.
SymbolMeaning
~bitwise negation
^bitwise exclusive or
&bitwise and
|bitwise or
<<left shift
>>right shift
The bitwise negation operator changes each 1 to 0 and 0 to 1.
php > print ~7;
-8
php > print ~-8;
7
The operator reverts all bits of a number 7. One of the bits also determines, whether the number is negative or not. If we negate all the bits one more time, we get number 7 again.
The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.
     00110
& 00011
= 00010
The first number is a binary notation of 6. The second is 3. The result is 2.
php > print 6 & 3;
2
php > print 3 & 6;
2
The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if either of the corresponding bits in the operands is 1.
     00110
| 00011
= 00111
The result is 00110 or decimal 7.
php > print 6 | 3;
7
The bitwise exclusive or operator performs bit-by-bit comparison between two nubmers. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.
     00110
^ 00011
= 00101
The result is 00101 or decimal 5.
php > print 6 ^ 3;
5
Finally, we also have bitwise shift operators. The bitwise shift operators shift bits to the right or left.
number << n : multiply number 2 to the nth power
number >> n : divide number by 2 to the nth power
These operators are also called arithmetic shift.
     00110
>> 00001
= 00011
We shift each of the bits of number six to the right. It is equal to dividing the six by 2. The result is 00011 or decimal 3.
php > print 6 >> 1;
3
     00110
<< 00001
= 01100
We shift each of the bits of number six to the left. It is equal to multiplying the number six by 2. The result is 01100 or decimal 12.
php > print 6 << 1;
12

Compound assignment operators

The compound assignment operators consist of two operators. They are shorthand operators.
php > $i = 1;
php > $i = $i + 1;
php > print $i;
2
php > $i += 1;
php > print $i;
3
The += compound operator is one of these shorthand operators. They are less readable than the full expressions but experienced programmers often use them.
Other compound operators are:
-=   *=   .=   /=    %=   &=   |=   ^=   >>=   <<=   

Operator precedence

The operator precedence tells us which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions.
What is the outcome of the following expression? 28 or 40?
 3 + 5 * 5
Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.
(3 + 5) * 5
To change the order of evaluation, we can use square brackets. Expressions inside square brackets are always evaluated first.
The following list shows common PHP operators ordered by precedence (highest precedence first):
Operator(s) Description
++ -- increment/decrement
(int) (float) (string) (array) (object) (bool) casting
! logical "not"
* / % arithmetic
+ - . arithmetic and string
<< >> bitwise
< <= > >= <> comparison
== != === !== comparison
&& logical "and"
|| logical "or"
? : ternary operator
= += -= *= /= .= %= assignment
and logical "and"
xor logical "xor"
or logical "or"
, comma operator
Operators on the same line in the list have the same precedence.
<?php

print 3 + 5 * 5;
print "\n";
print (3 + 5) * 5;
print "\n";

var_dump(! True or True);
var_dump(! (True or True));

?>
In this code example, we show some common expressions. The outcome of each expression is dependent on the precedence level.
var_dump(! True or True);
In this case, the negation operator has a higher precedence. First, the first True value is negated to False, than the or operator combines False and True, which gives True in the end.
$ php precedence.php 
28
40
bool(true)
bool(false)
The relational operators have a higher precedence than logical operators.
<?php

$a = 1;
$b = 2;

if ($a > 0 and $b > 0) {

echo "\$a and \$b are positive integers\n";
}

?>
The and operator awaits two boolean values. If one of the operands would not be a boolean value, we would get a syntax error. In PHP, the relational operators are evaluated first. The logical operator then.
$ php positive.php 
$a and $b are positive integers

Associativity

Sometimes the precedence is not satisfactory to determine the outcome of an expression. There is another rule called associativity. The associativity of operators determines the order of evaluation of operators with the sameprecedence level.
9 / 3 * 3
What is the outcome of this expression? 9 or 1? The multiplication, deletion and the modulo operator are left to right associated. So the expression is evaluated this way: (9 / 3) * 3 and the result is 9.
Arithmetic, boolean, relational and bitwise operators are all left to right associated.
On the other hand, the assignment operator is right associated.
php > $a = $b = $c = $d = 0;
php > echo $a, $b, $c, $d;
0000
If the association was left to right, the previous expression would not be possible.
The compound assignment operators are right to left associated.
php > $j = 0;
php > $j *= 3 + 1;
php > print $j;
0
You might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and than the compound assignment operator is applied.

Other operators

PHP has a silence ( @ ) operator. It is used to turn off error messaging. It is typically used with network or database connections. This operator should be used with caution, because it can lead to debugging issues.
php > echo 3 / 0;

Warning: Division by zero in php shell code on line 1
php > echo @ (3 / 0);
php >
In the first case, we receive a division by zero error message. In the second case, the @ operator turns off the error message.
The reference ( & ) operator. It creates a reference to an object.
php > $a = 12;
php > $b = &$a;
php > echo $b;
12
php > $b = 24;
php > echo $b;
24
php > echo $a;
24
In the above example, we pass a value to $a variable and pass a reference to the $a to the $b variable.
php > $b = &$a;
We create a new variable $b pointing to the $a variable. In other words, we create an alias for the $a variable.
php > $b = 24;
php > echo $b;
24
php > echo $a;
24
Assigning a new value to $b will also affect the $a.
The backtick ( ` ) operator. It is used to execute commands. It is identical to the shell_exec() function call.
php > $list = `ls -l`;
php > echo $list;
total 48
-rw-r--r-- 1 vronskij vronskij 127 2009-12-07 11:25 andop.php
-rw-r--r-- 1 vronskij vronskij 174 2009-12-07 10:48 arithmetic.php
-rw-r--r-- 1 vronskij vronskij 86 2010-01-16 15:11 atoperator.php
-rw-r--r-- 1 vronskij vronskij 106 2009-12-07 12:25 compare.php
...
We execute an ls command, which on Unix systems lists the contents of the current directory.
In this part of the PHP tutorial, we covered the PHP operators.
Continue Reading

Strings in PHP

In this part of the PHP programming tutorial, we will work with string data in more detail.
Strings are the most important data types in computer languages. That is why we dedicate a whole chapter to working with strings in PHP.

String literals

A string literal is the notation for representing a string value within the text of a computer program. In PHP programming language, strings can be created with single quotes, double quotes or using the heredoc syntax.
<?php

$a = "PHP";
$b = 'PERL';

echo $a, $b;

?>
In this code example, we create two strings and assign them to $a, $b variables. We print them with the echo command. The first string is created with the double quote delimiters, the second one with single quotes.
The next example will create a string with a heredoc syntax. The heredoc preserves the line breaks and other whitespace (including indentation) in the text. The heredoc is created with <<< followed by a delimiting identifier, followed, starting on the next line, by the text to be quoted, and then closed by the same identifier on its own line. The closing identifier must not be indented. It can only contain alphanumeric characters and underscores, and must start with a non-digit character or underscore.
<?php

$str = <<<TEXT
"That is just as I intended." Vautrin said. "You know quite well what
you are about. Good, my little eaglet! You are born to command, you
are strong, you stand firm on your feet, you are game! I respect you."
TEXT;

echo $str, "\n";

?>
The semicolon is optional.
echo "PHP " . "language"; # prints PHP language
PHP uses the dot (.) operator to concatenate two strings.

Escape characters

An escape character is a single character designated to invoke an alternative interpretation on immediately subsequent characters in a character sequence. (Wikipedia)
php > echo "   bbb\raaa";
aaabbb
The carriage return \r is a control character for end of line return to beginning of line.
<?php
echo "Incompatible, it don't matter though\n'cos someone's bound to hear my cry\n";
echo "Speak out if you do\nYou're not easy to find\n";
?>
The new line is a control character, which begins a new line of text.
$ php strophe.php 
Incompatible, it don't matter though
'cos someone's bound to hear my cry
Speak out if you do
You're not easy to find
echo "Towering\tinferno"; # Towering    inferno
The horizontal tab puts a space between text.
"Johnie's dog"
'Johnie\'s dog'
Single and double quotes can be nested. Or in case we use only single quotes, we can use the backslash to escape the default meaning of a single quote.
<?php

$text = "
\"That is just as I intended.\" Vautrin said. \"You know quite well what
you are about. Good, my little eaglet! You are born to command, you
are strong, you stand firm on your feet, you are game! I respect you.\"
";

echo $text;
?>
In this example, we have a multiline text, which includes direct speech. The double quotes are escaped with the backslash character.
php > $var = 233;
php > echo "$var";
233
php > echo "\$var is $var";
$var is 233
The dollar sign $ has also a special meaning in PHP. It denotes a variable. If a variable is used inside a string, it is interpolated, e.g. the value of the variable is used. To echo a variable name, we escape the $ character \$.

Operations on strings

PHP has a large number of useful useful built-in functions that can be used for working with strings.
echo strlen("Eagle"); # prints 5
echo strtoupper("Eagle"); # prints EAGLE
echo strtolower("Eagle"); # prints eagle
Here we use three functions. The strlen() function returns a number of characters in the string. The strtoupper() converts characters to uppercase letters, the strtolower() converts characters to lowercase letters.
<?php

$sentence = "There are 22 apples";

$alphas = 0;
$digits = 0;
$spaces = 0;

$length = strlen($sentence);

for ($i = 0; $i < $length; $i++)
{

$c = $sentence[$i];
if (ctype_alpha($c)) $alphas++;
if (ctype_digit($c)) $digits++;
if (ctype_space($c)) $spaces++;

}


echo "There are $length characters.\n";
echo "There are $alphas alphabetic characters.\n";
echo "There are $digits digits.\n";
echo "There are $spaces spaces.\n";

?>
In our example, we have a string sentence. We calculate the absolute number of characters, number of alphabetic characters, digits and spaces in the sentence. To do this, we use functions: strlen(), ctype_alpha(), ctype_digit() and ctype_space().
$ php letters.php 
There are 19 characters.
There are 14 alphabetic characters.
There are 2 digits.
There are 3 spaces.
Next, we cover the substr() function.
echo substr("PHP language", 0, 3); # prints PHP
echo substr("PHP language", -8); # prints language
The function returns a part of a string. The first parameter is the specified string. The second parameter is the start of the substring. The third parameter is optional. It is the length of the returned substring. Default is to the end of the string.
The str_repeat() function repeats a string a specified number of times.
<?php

echo str_repeat("#", 18);
echo "\nProject Neurea\n";
echo "Priority high\n";
echo "Security maximum\n";
echo str_repeat("#", 18);
echo "\n";

?>
We use the str_repeat() function to create two lines of the # character.
$ php repeat.php 
##################
Project Neurea
Priority high
Security maximum
##################
In the next example, we will randomly modify a string.
<?php

$string = "ZetCode";

echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";

?>
The str_shuffle() randomly shuffles a string.
$ php shuffle.php 
CteZeod
teZCdeo
ZteoCed
odCteZe
oCdetZe
eedtCZo
edCetoZ
The explode() function is used to split a string into parts. It returns an array of split string parts.
<?php

$text = "Rastignac heard him in dazed bewilderment;
he could not find a word in reply. Just then Goriot
came in, and Bianchon and a few of the
boarders likewise appeared.";

$sentences = explode(".", $text);

echo $sentences[0];
echo $sentences[1];

?>
We have two sentences. Each sentence is ended with a full stop.
 $sentences = explode(".", $text);
Here we split the text with the explode() function. The function will cut a string into pieces, whenever it finds the dot (.) character.
<?php

echo "Ajax Amsterdam" . " - " . "Inter Milano " . "2:3\n";
echo "Real Madridi" . " - " . "AC Milano " . "3:3\n";
echo "Dortmund" . " - " . "Sparta Praha ". "2:1\n";

?>
We concatenate strings with the dot operator.
$ php teams1.php
Ajax Amsterdam - Inter Milano 2:3
Real Madridi - AC Milano 3:3
Dortmund - Sparta Praha 2:1
The output does not look very good. We will change it so that it looks better.
<?php

$teams = array(
array("Ajax Amsterdam", "Inter Milano"),
array("Real Madrid", "AC Milano"),
array("Dortmund", "Sparta Praha")
);

$results = array("2:3", "3:3", "2:1");

$i = 0;

foreach ($teams as $team) {
echo str_pad($team[0], 14);
echo str_pad("-", 3, " ", STR_PAD_BOTH);
echo str_pad($team[1], 14);
echo str_pad($results[$i], 3, " ", STR_PAD_LEFT);
echo "\n";
$i++;
}
?>
We improve the output format with the str_pad() function. It adds a specified string (in our case a space) to the left of the string, to the right or to both sides.
$ php teams2.php 
Ajax Amsterdam - Inter Milano 2:3
Real Madrid - AC Milano 3:3
Dortmund - Sparta Praha 2:1
We manage to give a more nicely formatted output.

String formatting

String formatting or string interpolation is dynamic putting of various values into a string.
<?php

printf("There are %d oranges and %d apples in the basket.\n", 12, 32);

?>
We use the %d formatting specifier. The d character says, we are expecting an integer. After the string, we put a modulo operator and an argument. In this case an integer value.
$ php fruits.php 
There are 12 oranges and 32 apples in the basket.
In the next example, we will interpolate a float and a string value.
<?php

printf("Height: %f %s\n", 172.3, "cm");

?>
The formatting specifier for a float value is %f and for a string %s.
$ php height.php 
Height: 172.300000 cm
We might not like the fact, that the number in the previous example has 6 decimal places by default. We can control the number of the decimal places in the formatting specifier.
<?php

printf("Height: %.1f %s\n", 172.3, 'cm');

?>
The decimal point followed by an integer controls the number of decimal places. In our case, the number will have exactly one decimal place.
$ php height2.php 
Height: 172.3 cm
The following example shows other formatting options.
<?php

# hexadecimal
printf("%x\n", 300);

# octal
printf("%o\n", 300);

# scientific
printf("%e\n", 300000);

?>
The first interpolation works with hexadecimal numbers. The x character will format the number in hexadecimal notation. The o character shows the number in octal format. The e character will show the number in scientific format.
$ php formatting.php 
12c
454
3.000000e+5
The next example will print three columns of numbers.
<?php

foreach (range(1,11) as $num) {
echo $num , " ", $num*$num, " ",
$num*$num*$num, "\n";
}

?>
The numbers are left justified and the output look terrible.
$ php columns.php 
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
11 121 1331
To correct this, we use the width specifier. The width specifier defines the minimal width of the object. If the object is smaller than the width, it is filled with spaces.
<?php

foreach (range(1,11) as $num) {
printf("%2d %3d %4d\n", $num, $num*$num, $num*$num*$num);
}

?>
Now the output looks OK. 2 says that the first column will be 2 characters wide.
$ php columns2.php 
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
11 121 1331
This part of the PHP tutorial covered strings.
Continue Reading

About PHP data types

In this part of the PHP tutorial, we will talk about data types.
Computer programs work with data. Spreadsheets, text editors, calculators or chat clients. Tools to work with various data types are essential part of a modern computer language. According to the wikipedia definition, a data type is a set of values, and the allowable operations on those values.
PHP has eight data types:
Scalar types
  • boolean
  • integer
  • float
  • string
Compound types
  • array
  • object
Special types
  • resources
  • NULL
Unlike in languages like Java, C or Visual Basic, in PHP you do not provide an explicit type definition for a variable. A variable's type is determined at runtime by PHP. If you assign a string to a variable, it becomes a string variable. Later if you assign an integer value, the variable becomes an integer variable.

Boolean values

There is a duality built in our world. There is a Heaven and Earth, water and fire, jing and jang, man and woman, love and hatred. In PHP the boolean data type is a primitive data type having one of two values: True or False. This is a fundamental data type. Very common in computer programs.
Happy parents are waiting a child to be born. They have chosen a name for both possibilities. If it is going to be a boy, they have chosen John. If it is going to be a girl, they have chosen Victoria.
<?php

$male = False;

$r = rand(0, 1);

$male = $r ? True: False;

if ($male) {
echo "We will use name John\n";
} else {
echo "We will use name Victoria\n";
}
?>
The script uses a random integer generator to simulate our case.
$r = rand(0, 1);
The rand() function returns a random number from the given integer boundaries. In our case 0 or 1.
$male = $r ? True: False;
We use the ternary operator to set a $male variable. The variable is based on the random $r value. If $r equals to 1, the $male variable is set to True. If $r equals to 0, the $male variable is set to False.
if ($male) {
echo "We will use name John\n";
} else {
echo "We will use name Victoria\n";
}
We print the name. The if command works with boolean values. If the variable $male is True, we print the "We will use name John" to the console. If it has a False value, we print the other string.
The following script shows some common values that are considered to be True or False. For example, empty string, empty array, 0 are considered to be False.
<?php
class Object {};

var_dump((bool) "");
var_dump((bool) 0);
var_dump((bool) -1);
var_dump((bool) "PHP");
var_dump((bool) array(32));
var_dump((bool) array());
var_dump((bool) "false");
var_dump((bool) new Object());
var_dump((bool) NULL);
?>
In this script, we inspect some values in a boolean context. The var_dump() function shows information about a variable. The (bool) construct is called casting. In its casual context, the 0 value is a number. In a boolean context, it is False. The boolean context is when we use (bool) casting, when we use certain operators (negation, comparison operators) and when we use if/else, while keywords.
$ php boolean.php
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
Here is the outcome of the script.

Integers

Integers are a subset of the real numbers. They are written without a fraction or a decimal component. Integers fall within a set Z = {..., -2, -1, 0, 1, 2, ...} Integers are infinite.
In computer languages, integers are primitive data types. Computers can practically work only with a subset of integer values, because computers have finite capacity. Integers are used to count discrete entities. We can have 3, 4, 6 humans, but we cannot have 3.33 humans. We can have 3.33 kilograms.
Integers can be specified in three different notations in PHP. Decimal, hexadecimal and octal. Octal values are preceded by 0, hexadecimal by 0x.
<?php

$var1 = 31;
$var2 = 031;
$var3 = 0x31;

echo "$var1\n";
echo "$var2\n";
echo "$var3\n";

?>
We assign 31 to three variables using three notations. And we print them to the console.
$ php notation.php 
31
25
49
The default notation is the decimal. The script shows these three numbers in decimal.
Integers in PHP have a fixed maximum size. The size of integers is platform dependent. PHP has built-in constants to show the maximum size of an integer.
$ uname -mo
i686 GNU/Linux
$ php -a
Interactive shell

php > echo PHP_INT_SIZE;
4
php > echo PHP_INT_MAX;
2147483647
php >
On my 32bit Ubuntu system, an integer value size is four bytes. The maximum integer value is 2147483647.
In Java and C, if an integer value is bigger than the maximum value allowed, integer overflow happens. PHP works differently. In PHP, the integer becomes a float number. Floating point numbers have greater boundaries.
<?php

$var = PHP_INT_MAX;

echo var_dump($var);
$var++;
echo var_dump($var);

?>
We assign a maximum integer value to the $var variable. We increase the variable by one. And we compare the contents.
$ php boundary.php 
int(2147483647)
float(2147483648)
As we have mentioned previously, internally, the number becomes a floating point value.
In Java, the value after increasing would be -2147483648. This is where the term integer overflow comes from. The number goes over the top and becomes the smallest negative integer value assignable to a variable.
If we work with integers, we deal with discrete entities. We would use integers to count apples.
<?php

# number of baskets
$baskets = 16;

# number of apples in each basket
$apples_in_basket = 24;

# total number of apples
$total = $baskets * $apples_in_basket;

echo "There are total of $total apples \n";
?>
In our script, we count the total amount of apples. We use the multiplication operation.
$ php apples.php 
There are total of 384 apples
The output of the script.

Floating point numbers

Floating point numbers represent real numbers in computing. Real numbers measure continuous quantities. Like weight, height or speed. Floating point numbers in PHP can be larger than integers and they can have a decimal point. The size of a float is platform dependent.
We can use various syntax to create floating point values.
<?php

$a = 1.245;
$b = 1.2e3;
$c = 2E-10;
$d = 1264275425335735;

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);

?>
In this example, we have two cases of notations, that are used by scientists to denote floating point values. Also the $d variable is assigned a large number, so it is automatically converted to float type.
$ php floats.php 
float(1.245)
float(1200)
float(2.0E-10)
float(1264275425340000)
This is the output of the above script.
According to the documentation, floating point numbers should not be tested for equality. We will show an example why.
$ php -a
Interactive shell

php > echo 1/3;
0.333333333333
php > $var = (0.333333333333 == 1/3);
php > var_dump($var);
bool(false)
php >
In this example, we compare two values that seem to be identical. But they yield unexpected result.
Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?
<?php

# 100m is 0.1 km

$distance = 0.1;

# 9.87s is 9.87/60*60 h

$time = 9.87 / 3600;

$speed = $distance / $time;

echo "The average speed of a sprinter is $speed \n";

?>
In this example, it is necessary to use floating point values.
$speed = $distance / $time;
To get the speed, we divide the distance by the time.
$ php sprinter.php 
The average speed of a sprinter is 36.4741641337
This is the output of the sprinter script. 36.4741641337 is a floating point number.

Strings

String is a data type representing textual data in computer programs. Probably the single most important data type in programming.
Since string are very important in every programming language, we will dedicate a whole chapter to them. Here we only drop a small example.
<?php

$a = "PHP ";
$b = 'PERL';

echo $a, $b;
echo "\n";

?>
We can use single quotes and double quotes to create string literals.
$ php strings.php 
PHP PERL
The script outputs two strings to the console. The \n is a special sequence, a new line. The effect of this character is like if you hit the enter key when typing text.

Arrays

Array is a complex data type which handles a collection of elements. Each of the elements can be accessed by an index. In PHP, arrays are more diverse. Arrays can be treated as arrays, lists or dictionaries. In other words, arrays are all what in other languages we call arrays, lists, dictionaries.
Because collections are very important in all computer languages, we dedicate two chapters to collections - arrays. Here we show only a small example.
<?php

$names = array("Jane", "Lucy", "Timea", "Beky", "Lenka");

print_r($names);

?>
The array keyword is used to create a collection of elements. In our case we have names. The print_r function prints a human readable information about a variable to the console.
$ php init.php 
Array
(
[0] => Jane
[1] => Lucy
[2] => Timea
[3] => Beky
[4] => Lenka
)
Output of the script. The numbers are indeces by which we can access the names.

Objects

So far, we have been talking about built-in data types. Objects are user defined data types. Programmers can create their data types that fit their domain. More about objects in chapter about object oriented programming, OOP.

Resources

Resources are special data types. They hold a reference to an external resource. They are created by special functions. Resources are handlers to opened files, database connections or image canvas areas.

NULL

There is another special data type - NULL. Basically, the data type means non existent, not known or empty.
In PHP, a variable is NULL in three cases:
  • it was not assigned a value
  • it was assigned a special NULL constant
  • it was unset with the unset() function
<?php

$a;
$b = NULL;

$c = 1;
unset($c);

$d = 2;

if (is_null($a)) echo "\$a is null\n";
if (is_null($b)) echo "\$b is null\n";
if (is_null($c)) echo "\$c is null\n";
if (is_null($d)) echo "\$d is null\n";

?>
In our example, we have four variables. Three of them are considered to be NULL. We use the is_null() function to determine, if the variable is NULL.
$ php null.php 
$a is null
$b is null
$c is null
Outcome of the script.

Type casting

We often work with multiple data types at once. Converting one data type to another one is a common job in programming. Type conversion or typecasting refers to changing an entity of one data type into another. There are two types of conversion. Implicit and explicit. Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler.
php > echo "45" + 12;
57
php > echo 12 + 12.4;
24.4
In the above example, we have two examples of implicit type casting. In the first statement, the string is converted to integer and added to the second operand. If either operand is a float, then both operands are evaluated as floats, and the result will be a float.
Explicit conversion happens, when we use the cast constructs, like (boolean).
php > $a = 12.43;
php > var_dump($a);
float(12.43)
php > $a = (integer) $a;
php > var_dump($a);
int(12)
php > $a = (string) $a;
php > var_dump($a);
string(2) "12"
php > $a = (boolean) $a;
php > var_dump($a);
bool(true)
This code snippet shows explicit casting in action. First we assign a float value to a variable. Later we cast it to integer, string and finally boolean data type.
In this part of the PHP tutorial, we covered data types.
Continue Reading

PHP Programming tutorial Basics for Beginners

In this part of the PHP tutorial, we will talk about basic programming in PHP.
All the PHP code is surrounded by two delimiters, <?php and ?>. The 'php' string is optional but recommended.
<?php 

# PHP code

?>
PHP code is put between two delimiters.
<?php 

$a = 23;
print $a;

?>
This PHP script assigns a value to a variable. It prints it to the console. Note that we say console, because here we use the PHP_CLI command line interpreter. If you test these examples on the web, the output will be sent to the browser.
$a = 23;
We assign a value 23 to the $a variable. Each variable starts with a dollar character. This PHP code line is a statement. Each statement ends with a semicolon. In PHP, semicolons are not mandatory, like in Javascript or Ruby. They are obligatory.
print $a;
We print the $a variable to the console. The print keyword does not add a new line to the output. If we want a new line, we must put it manually. print keyword takes only one argument.
<?php 

$a = 23;
$b = 24;

echo $a, "\n", $b, "\n";

?>
In this script, we use the echo keyword. It is similar to the print keyword. Unlike the print keyword, it can take multiple arguments.
$a = 23;
$b = 24;
We define two variables.
echo $a, "\n", $b, "\n";
We print the variables to the console. We also include the new line characters. Arguments can be separated by commas.
$ php echo.php 
23
24
This is the output of the script.

Types

PHP is a weakly typed language. It works with types, but the programmer does not specify them when declaring variables. A data type is a one of various types of data, as double, integer, or boolean. Values of a certain data type are from a specific range of values stating the possible values for that type, the operations that can be done on that type, and the way the values of that type are stored. PHP works implicitly with data types. Programmers do not specify explicitly the data types.
<?php 

$a = "Jane";
echo "$a \n";

$a = 12;
echo "$a \n";

$a = 56.4;
echo "$a \n";

$a = true;
echo "$a \n";

?>
In this PHP script, we have an $a variable. First, we assign it a string, then an integer, a double and finally a boolean value. If we assign a string to a variable the PHP automatically creates a string variable.
$ php dynamic.php 
Jane
12
56.4
1
Running the script.
<?php 

$temperature = 12.4;
$name = "Jane";
$age = 17;
$values = array(1, 2, 3, 4, 5, 6);

class Being {};

$somebody = new Being();

echo gettype($temperature), "\n";
echo gettype($name), "\n";
echo gettype($age), "\n";
echo gettype($values), "\n";
echo gettype($somebody), "\n";

?>
In the above PHP script, we dynamically create five types.
$values = array(1, 2, 3, 4, 5, 6); 

class Being {};
This is an array and a class. Both types will be covered later in more detail.
echo gettype($temperature), "\n";
The gettype() function returns the type of the variable in question.
$ php gettype.php 
double
string
integer
array
object
This script lists the basic types of the PHP language.

Constants

In PHP, we can create constants. A constant is a name for a value that, unlike a variable, cannot be reassociated with a different value. We use the define() function to create constants in PHP.
<?php 

define("BLUE", "0000FF");

echo BLUE, "\n";

echo defined("BLUE");
echo "\n";

?>
In this PHP script, we define a BLUE constant.
define("BLUE", "0000FF");
Here we define the BLUE constant. It is a convention to write constants in uppercase letters.
echo BLUE, "\n";
Here we use it. Note that constants are not preceded by ($) dollar character.
echo defined("BLUE");
We have used another function, the defined() function. It checks, if a particular constant exists. Returns true, if it does.
$ php constant.php 
0000FF
1
Running the example gives the above output.
PHP also has some predefined constants.
<?php 

echo TRUE;
echo "\n";
echo PHP_VERSION;
echo "\n";
echo PHP_OS;
echo "\n";
echo __LINE__;
echo "\n";
echo __FILE__;
echo "\n";
echo DIRECTORY_SEPARATOR;
echo "\n";
echo PHP_DATADIR;
echo "\n";

?>
Here we print some built-in PHP constants. For example, the PHP_OSconstant prints the OS version on which the PHP was built.
$ php constants.php 
1
5.2.6-2ubuntu4.6
Linux
9
/home/vronskij/programming/php/basics/constants.php
/
${prefix}/share
On my system, I get this output.

Variable interpolation

Next, we will define interpolation. Variable interpolation is replacing variables with their values inside string literals. Another names for variable interpolation are: variable substitution and variable expansion.
<?php 

$age = 17;

echo "Jane is $age years old\n";

?>
The $age variable is replaced with the value 17 in the string.
$ php interpolation.php 
Jane is 17 years old
<?php 

$age = 17;

echo 'Jane is $age years old\n';

?>
However, this does not work, if we use the single quotes. In this case, no interpolation happens and no special characters are working.
$ php interpolation2.php 
Jane is $age years old\n$
We see a verbatim output of the string.

Including files

PHP code is split in multiple files for bigger programs. We use the include statement to join various PHP files.
<?php 

define("VERSION", 1.12);

function get_max($x, $y) {
if ($x > $y) {
return $x;
} else {
return $y;
}
}

?>
Let's say, we have a common.php file, in which we define some constants and functions.
<?php 

include "common.php";

echo "The version is " . VERSION . "\n";

$a = 5;
$b = 3;

echo get_max($a, $b), "\n";

?>
And we have another file, which wants to use the aforementioned definitions.
include "common.php";
We simply include the definitions to our file with the include keyword. We must specify the exact path to the common.php file. In our simple case, both files are in the same directory.
This chapter covered some basics of the PHP language.
Continue Reading

Step by step PHP tutorials for beginners

Computer languages, like human languages, have a lexical structure. A source code of a PHP script consists of tokens. Tokens are atomic code elements. In PHP language, we have comments, variables, literals, operators, delimiters and keywords.

Comments

Comments are used by humans to clarify the source code. All comments in PHP follow the # character.
<?php

# comments.php
# author Jan Bodnar
# ZetCode 2009

echo "This is comments.php script\n";

?>
Everything that follows the # character is ignored by the PHP interpreter.
// comments.php
// author Jan Bodnar
// ZetCode 2009

/*
comments.php
author Jan Bodnar
ZetCode 2009
*/
PHP also recognizes the comments from the C language.

White space

White space in PHP is used to separate tokens in PHP source file. It is used to improve readability of the source code.
public $isRunning;
White spaces are required in some places. For example between the access specifier and the variable name. In other places, it is forbidden. It cannot be present in variable identifiers.
$a=1;
$b = 2;
$c = 3;
The amount of space put between tokens is irrelevant for the PHP interpreter.
$a = 1;
$b = 2; $c = 3;
$d
=
4;
We can put two statements into one line. Or one statement into three lines. However, source code should be readable for humans. There are accepted standards of how to lay out your source code.

Semicolon

A semicolon is used to mark the end of a statement in PHP. It is mandatory.
$a = 34;
$b = $a * 34 - 34;
echo $a;
Here we have three different PHP statements. The first is an assignment. It puts a value into the $a variable. The second one is an expression. The expression is evaluated and the output is given to the $b variable. The third one is a command. It prints the $a variable.

Variables

A variable is an identifier, which holds a value. In programming we say, that we assign a value to a variable. Technically speaking, a variable is a reference to a computer memory, where the value is stored. In PHP language, a variable can hold a string, a number or various objects like a function or a class. Variables can be assigned different values over time.
Variables in PHP consist of the $ character and a label. A label can be created from alphanumeric characters and an underscore (_) character. A variable cannot begin with a number. The PHP interpreter can then distinguish between a number and a variable more easily.
$Value
$value2
$company_name
These were valid identifiers.
$12Val
$exx$
$first-name
These were examples of invalid identifiers.
The variables are case sensitive. This means, that $Price, $price, and $PRICEare three different identifiers.
<?php

$number = 10;
$Number = 11;
$NUMBER = 12;

echo $number, $Number, $NUMBER;

echo "\n";

?>
In our script, we assign three numeric values to three variables and print them.
101112
This is the output of the script.

A literal

A literal is any notation for representing a value within the PHP source code. Technically, a literal will be assigned a value at compile time, while a variable will be assigned at runtime.
$age = 29;
$nationality = "Hungarian";
Here we assign two literals to variables. Number 29 and string Hungarian are literals.
<?php

$name1 = "Jane ";
$age1 = 17;

$name2 = "Rose ";
$age2 = 16;

echo "Patrick 34\n";
echo "Luke 22\n";

echo $name1, $age1, "\n";
echo $name2, $age2, "\n";

?>
If we do not assign a literal to a variable, there is no way, how we can work with it. It is dropped.
$ php literals.php
Patrick 34
Luke 22
Jane 17
Rose 16
This is the output of the literals.php script.

Operators

An operator is a symbol used to perform an action on some value. (answers.com)
+    -    *    /    %    ++    --
= += -= *= /= .= %=
== != >< > < >= <=
&& || ! xor or
& ^ | ~ . << >>
These are PHP operators. We will talk about operators later in the tutorial.

Delimiters

A delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data stream. (wikipedia)
$a = "PHP";
$b = 'Java';
The single and double characters are used to mark the beginning and the end of a string.
function setDate($date) {
$this->date = $data;
}

if ( $a > $b) {
echo "\$a is bigger than \$b";
}

Parentheses are used to mark the function signature. The signature is the function parameters. Curly brackets are used to mark the beginning and the end of the function body. They are also used in flow control.
$a = array(1, 2, 3);
echo $a[1];
The square brackets are used to mark the array index.
/*
Author Jan Bodnar
December 2009
ZetCode
*/
/* */ delimiters are used to provide C style comments in PHP.
<?php
// PHP code
?>
The <?php and ?> delimiters are used to delimit PHP code in a file.

Keywords

A keyword is a reserved word in the PHP programming language. Keywords are used to perform a specific task in the computer program. For example, print a value, do repetitive tasks or perform logical operations. A programmer cannot use a keyword as an ordinary variable.
The following is a list of PHP keywords.
abstract    and          array()     as          break
case catch class clone const
continue declare default do else
elseif enddeclare endfor endforeach endif
endswitch endwhile extends final for
foreach function global goto if
implements interface instanceof namespace new
or private protected public static
switch throw try use var
while xor
The following is a list of PHP compile time constants.
__CLASS__    __DIR__       __FILE__    __FUNCTION__ 
__METHOD__ __NAMESPACE__
Next we have other language constructs.
die()           echo()          empty()     exit()      eval()
include() include_once() isset() list() require()
require_once() return() print() unset()
In this part of the PHP tutorial, we covered the basic lexis for the PHP language.
Continue Reading

MySQL Transaction support for PHP

A transaction is an atomic unit of database operations against the data in one or more databases. The effects of all the SQL statements in a transaction can be either all committed to the database or all rolled back.
The MySQL database has different types of storage engines. The most common are the MyISAM and the InnoDB engines. The MyISAM is the default one. There is a trade-off between data security and database speed. The MyISAM tables are faster to process and they do not support transactions. On the other hand, the InnoDB tables are more safe against the data loss. They support transactions. They are slower to process.
<?php

mysql_connect('localhost', 'testuser', 'test623')
or die("cannot connect to database\n");

mysql_select_db("testdb") or die(mysql_error());

$r1 = mysql_query("UPDATE Writers SET Name = 'Leo Tolstoy' WHERE Id = 1")
or die(mysql_error());

$r2 = mysql_query("UPDATE Writers SET Name = 'Boris Pasternak' WHERE Id = 2")
or die(mysql_error());

$r3 = mysql_query("UPDATE Writer SET Name = 'Leonid Leonov' WHERE Id = 3")
or die(mysql_error());

mysql_close();

?>
In this script, we try to update three rows. The storage engine of the table is MyISAM.
$r1 = mysql_query("UPDATE Writers SET Name = 'Leo Tolstoy' WHERE Id = 1")
or die(mysql_error());

$r2 = mysql_query("UPDATE Writers SET Name = 'Boris Pasternak' WHERE Id = 2")
or die(mysql_error());
Here we want to change names of authors for rows 1 and 2.
$r3 = mysql_query("UPDATE Writer SET Name = 'Leonid Leonov' WHERE Id = 3")
or die(mysql_error());
There is an error in the SQL statement. There is no Writer table.
$ php update.php
Table 'testdb.Writer' doesn't exist

mysql> SELECT * FROM Writers;
+----+-------------------+
| Id | Name |
+----+-------------------+
| 1 | Leo Tolstoy |
| 2 | Boris Pasternak |
| 3 | Lion Feuchtwanger |
| 4 | Emile Zola |
| 5 | Truman Capote |
| 6 | O'Neill |
+----+-------------------+
6 rows in set (0.00 sec)
Running the script gives an error. But as we see, the first two rows already were changed.
In the last example of this tutorial, we are going to recreate the Writers table. This time, the table will be of InnoDB type. InnoDB MySQL database tables support transactions.
DROP TABLE Writers;

CREATE TABLE IF NOT EXISTS Writers(Id INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(25)) ENGINE=INNODB;

INSERT INTO Writers(Name) VALUES('Jack London');
INSERT INTO Writers(Name) VALUES('Honore de Balzac');
INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger');
INSERT INTO Writers(Name) VALUES('Emile Zola');
INSERT INTO Writers(Name) VALUES('Truman Capote');
This is writers.sql file. It is used to recreate the Writers table.
mysql> source writers.sql
Query OK, 0 rows affected (0.03 sec)

Query OK, 0 rows affected (0.10 sec)

Query OK, 1 row affected (0.02 sec)

Query OK, 1 row affected (0.03 sec)

Query OK, 1 row affected (0.02 sec)

Query OK, 1 row affected (0.02 sec)

Query OK, 1 row affected (0.02 sec)
We can use the source commnad to load and execute the sql script.
<?php

mysql_connect('localhost', 'testuser', 'test623')
or die("cannot connect to database\n");

mysql_select_db("testdb") or die(mysql_error());

mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");

$r1 = mysql_query("DELETE FROM Writers WHERE Id = 3")
or die(mysql_error());

$r2 = mysql_query("DELETE FROM Writers WHERE Id = 4")
or die(mysql_error());

$r3 = mysql_query("DELETE FROM Writer WHERE Id = 5")
or die(mysql_error());

if ($r1 and $r2 and $r3) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}

mysql_close();

?>
Now, we are going to execute the above script. We want to delete three rows from the table. The third SQL statement has an error.
mysql_query("START TRANSACTION");
The START TRANSACTION statement starts a new transaction. All changes must be made permanent with the COMMIT statement or ignored with the ROLLBACK statement.
if ($r1 and $r2 and $r3) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
We commit the statements only if all SQL statements three returned True. Otherwise, we roll them back. In our case the $r3 variable holds False, so the statements are not made permanent and the rows are not deleted from the table.
$ php transaction.php
Table 'testdb.Writer' doesn't exist

mysql> SELECT * FROM Writers;
+----+-------------------+
| Id | Name |
+----+-------------------+
| 1 | Jack London |
| 2 | Honore de Balzac |
| 3 | Lion Feuchtwanger |
| 4 | Emile Zola |
| 5 | Truman Capote |
+----+-------------------+
5 rows in set (0.00 sec)
The error occurred before we have committed the changes to the database. The ROLLBACK statement was called and no deletions took place.
Continue Reading

Escaping characters From MySQL to PHP

We will have a small example demonstrating how to escape characters. There are some characters which are considered to be unsafe in a database environment. One of them is a single quote character.
mysql> CREATE TABLE IF NOT EXISTS Authors(Id INT PRIMARY KEY AUTO_INCREMENT, 
-> Name VARCHAR(25)) ENGINE=InnoDB;
Query OK, 0 rows affected (0.09 sec)
For the example, we create an Authors table.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysql_connect($host, $user, $pass);

if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Connection established\n";
}

$r2 = mysql_select_db($db);

if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Database selected\n";
}

$name = "O'Neill";
$name_es = mysql_real_escape_string($name);

$query = "INSERT INTO Authors(Name) VALUES('$name_es')";
$rs = mysql_query($query);

if (!$rs) {
echo "Could not execute query: $query\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}

mysql_close();

?>
We insert a new author to the Authors table. The name of the author is O'Neill. The name has an unsafe single quote character.
$name_es = mysql_real_escape_string($name);
Thay is why we use the mysql_real_escape_string() function to escape this character.
$query = "INSERT INTO Authors(Name) VALUES('$name_es')";
$rs = mysql_query($query);
We create the statement and execute it.
mysql> SELECT * FROM Authors;
+----+---------+
| Id | Name |
+----+---------+
| 1 | O'Neill |
+----+---------+
1 row in set (0.00 sec)
The name has been successfully written to the table.

Column headers

Next we will show, how to print column headers with the data from the database table.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysql_connect($host, $user, $pass);

if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Connection established\n";
}

$r2 = mysql_select_db($db);

if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Database selected\n";
}

$query = "SELECT * From Cars LIMIT 8";

$rs = mysql_query($query);

if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}

$cname1 = mysql_fetch_field($rs, 0);
$cname2 = mysql_fetch_field($rs, 1);
$cname3 = mysql_fetch_field($rs, 2);

printf("%3s %-11s %8s\n", $cname1->name, $cname2->name,
$cname3->name);

while ($row = mysql_fetch_row($rs)) {
printf("%3s %-11s %8s\n", $row[0], $row[1], $row[2]);
}

mysql_close();

?>
Again, we print the contents of the Writers table to the console. Now, we include the names of the columns too.
$cname1 = mysql_fetch_field($rs, 0);
$cname2 = mysql_fetch_field($rs, 1);
$cname3 = mysql_fetch_field($rs, 2);
To get a specific field name, we utilize the mysql_fetch_field() function. The function return an object containing column information.
printf("%3s %-11s %8s\n", $cname1->name, $cname2->name, 
$cname3->name);
The column names are printed and formatted. The name property contains the column name.
$ php columns.php
Connection established
Database selected
Query: SELECT * From Cars LIMIT 8 executed
Id Name Price
1 Audi 52642
2 Mercedes 57127
3 Skoda 9000
4 Volvo 29000
5 Bentley 350000
6 Citroen 21000
7 Hummer 41400
8 Volkswagen 21600
Ouput of the script.

Fields, rows

The following script counts the number of fields/columns and rows returned by a query.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysql_connect($host, $user, $pass);

if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Connection established\n";
}

$r2 = mysql_select_db($db);

if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Database selected\n";
}

$query = "SELECT * FROM Cars WHERE Id IN (1, 2, 3)";

$rs = mysql_query($query);

if (!$rs) {
echo "Could not execute query: $query\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}

echo "We have " . mysql_num_fields($rs) . " fields\n";
echo "We have " . mysql_num_rows($rs) . " rows\n";

print_r(mysql_fetch_row($rs));

mysql_close();

?>
We select three rows from the Cars table. We count the number of rows and columns returned by a query.
$query = "SELECT * FROM Cars WHERE Id IN (1, 2, 3)";
This is the query to be executed. It selects first three rows from the Cars table.
echo "We have " . mysql_num_fields($rs) . " fields\n";
The mysql_num_fields() returns the number of fields returned by a query.
echo "We have " . mysql_num_rows($rs) . " rows\n";
The mysql_num_rows() returns the number of rows returned by a query.
print_r(mysql_fetch_row($rs));
We print the contents of the array.
$ php fields_rows.php
Connection established
Database selected
Query: SELECT * FROM Cars WHERE Id IN (1, 2, 3) executed
We have 3 fields
We have 3 rows
Array
(
[0] => 1
[1] => Audi
[2] => 52642
)
Running the script.

Writing images

Some people prefer to put their images into the database, some prefer to keep them on the file system for their applications. Technical difficulties arise when we work with millions of images. Images are binary data. MySQL database has a special data type to store binary data called BLOB (Binary Large Object).
mysql> CREATE TABLE Images(Id INT PRIMARY KEY AUTO_INCREMENT, Data MEDIUMBLOB);
Query OK, 0 rows affected (0.06 sec)
For this example, we create a new table called Images.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysql_connect($host, $user, $pass);

if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Connection established\n";
}

$r2 = mysql_select_db($db);

if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Database selected\n";
}

$file = "woman.jpg";

$img = fopen($file, 'r');

if (!$img) {
echo "Cannot open file for writing\n";
trigger_error("Cannot open file for writing\n", E_USER_ERROR);
}

$data = fread($img, filesize($file));

if (!$data) {
echo "Cannot read image data\n";
trigger_error("Cannot read image data\n", E_USER_ERROR);
}

$es_data = mysql_real_escape_string($data);
fclose($img);

$query = "INSERT INTO Images(Id, Data) Values(1, '$es_data')";

$rs = mysql_query($query);

if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query successfully executed\n";
}

mysql_close();

?>
In the above script, we read a jpg image and insert it into the Images table.
$file = "woman.jpg";
This is the image name, that we read from the filesystem and write into the database. It is located in the same directory as the script name.
$img = fopen($file, 'r');

if (!$img) {
echo "Cannot open file for writing\n";
trigger_error("Cannot open file for writing\n", E_USER_ERROR);
}

$data = fread($img, filesize($file));

if (!$data) {
echo "Cannot read image data\n";
trigger_error("Cannot read image data\n", E_USER_ERROR);
}
We open and read the image. The fread()function returns the data as string.
$es_data = mysql_real_escape_string($data);
We escape unsafe characters.
fclose($img);
We close the handle to the image file.
$query = "INSERT INTO Images(Id, Data) Values(1, '$es_data')";

$rs = mysql_query($query);

if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query successfully executed\n";
}
We insert the data to the newly created Images table.

Reading images

In the previous example, we have inserted an image into the database table. Now we are going to read the image back from the table.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysql_connect($host, $user, $pass);

if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Connection established\n";
}

$r2 = mysql_select_db($db);

if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Database selected\n";
}

$query = "SELECT Data FROM Images WHERE Id=1";

$rs = mysql_query($query);

if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}

$row = mysql_fetch_row($rs);

$file = "woman2.jpg";

$img = fopen($file, 'wb');

if (!$img) {
echo "Cannot open file for writing\n";
trigger_error("Cannot open file for writing\n", E_USER_ERROR);
}

$r3 = fwrite($img, $row[0]);

if (!$r3) {
echo "Cannot write image to file\n";
trigger_error("Cannot write image to file\n", E_USER_ERROR);
}

fclose($img);

mysql_close();

?>
We read one image from the Images table.
$query = "SELECT Data FROM Images WHERE Id=1";
We select one record from the table.
$row = mysql_fetch_row($rs);
We fetch one row from the result set. There is only one row, containing the image data.
$file = "woman2.jpg";
We will create a new image file name called "woman2.jpg".
$img = fopen($file, 'wb');

if (!$img) {
echo "Cannot open file for writing\n";
trigger_error("Cannot open file for writing\n", E_USER_ERROR);
}
We open a writable binary file.
$r3 = fwrite($img, $row[0]);

if (!$r3) {
echo "Cannot write image to file\n";
trigger_error("Cannot write image to file\n", E_USER_ERROR);
}
We write the data to the filesystem using the fwrite()function.
Now we should have an image called "woman2.jpg" in our current directory. We can check if it is the same image, that we have inserted into the table.
Continue Reading

Retrieving data From MySQL to PHP

Now, that we have inserted some data into the database, we want to get it back.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysql_connect($host, $user, $pass);

if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Connection established\n";
}

$r2 = mysql_select_db($db);

if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Database selected\n";
}

$query = "SELECT * FROM Cars LIMIT 5";

$rs = mysql_query($query);

if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}

while ($row = mysql_fetch_assoc($rs)) {
echo $row['Id'] . " " . $row['Name'] . " " . $row['Price'] . "\n";
}

mysql_close();

?>
In this example, we retrieve five rows from the Cars table.
$query = "SELECT * FROM Cars LIMIT 5";
This SQL statement selects 5 rows from the Cars table.
$rs = mysql_query($query);
We execute the query with the mysql_query() function and retrieve the result set.
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}
If the query did not succeed, we generate an error message.
while ($row = mysql_fetch_assoc($rs)) {
echo $row['Id'] . " " . $row['Name'] . " " . $row['Price'] . "\n";
}
We loop through the result set and print the data to the console. The mysql_fetch_assoc() function returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows. In other words, the function call returns a row from the result set. This row is in the form of an associative array. The column names are keys to the associative array. When there are no more rows in the result set, the function returns FALSE and the while loop terminates.
$ php query.php
Connection established
Database selected
Query: SELECT * FROM Cars LIMIT 5 executed
1 Audi 52642
2 Mercedes 57127
3 Skoda 9000
4 Volvo 29000
5 Bentley 350000
This is the output of the example.

In the second example, we will fetch data with the mysql_fetch_row() function.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysql_connect($host, $user, $pass);

if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Connection established\n";
}

$r2 = mysql_select_db($db);

if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Database selected\n";
}

$query = "SELECT Id, Name, Price From Cars LIMIT 5";

$rs = mysql_query($query);

if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}

$nrows = mysql_num_rows($rs);

for ($i = 0; $i < $nrows; $i++) {
$row = mysql_fetch_row($rs);
echo $row[0];
echo " ";
echo $row[1];
echo " ";
echo $row[1];
echo "\n";
}

mysql_close();

?>
We get the first 5 rows from the Cars table.
$nrows = mysql_num_rows($rs);
The mysql_num_rows() function gets the number of rows from the result set.
for ($i = 0; $i < $nrows; $i++) {
$row = mysql_fetch_row($rs);
echo $row[0];
echo " ";
echo $row[1];
echo " ";
echo $row[1];
echo "\n";
}
We use the for loop to iterate over the returned rows. The mysql_fetch_row() function retrieves the row from the result set in the form of an enumerated array.
$ php query.php
Connection established
Query: SELECT * FROM Cars LIMIT 5 executed
1 Audi 52642
2 Mercedes 57127
3 Skoda 9000
4 Volvo 29000
5 Bentley 350000
Output.

In the following example, we show how to retrieve a specific row from a table.
<?php

$host = "localhost";
$user = "user12";
$pass = "34klq*";
$db = "mydb";

$r = mysql_connect($host, $user, $pass);

if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Connection established\n";
}

$r2 = mysql_select_db($db);

if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Database selected\n";
}

$name = "Volkswagen";

$query = sprintf("SELECT Id, Name, Price From Cars Where Name = '%s'",
mysql_real_escape_string($name));

$rs = mysql_query($query);

if (!$rs) {
echo "Could not execute query: $query\n";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}

while ($row = mysql_fetch_object($rs)) {
echo $row->Id;
echo " ";
echo $row->Name;
echo " ";
echo $row->Price;
echo "\n";
}

mysql_close();

?>
Developers must take security concerns into account when working with input from users. We must always process the data sent from outside world. Check for validity of the data.
$name = "Volkswagen";
In the script, we check, if we have "Volkswagen" in the Caras table. This value might come from an xml file or a web form. We will show, how to check it.
$query = sprintf("SELECT Id, Name, Price From Cars Where Name = '%s'", 
mysql_real_escape_string($name));
We build the SQL statement using the sprintf() function. We process the $name variable with the mysql_real_escape_string()function. This function escapes special characters in a string for use in an SQL statement. This prevents SQL injection attacks and data corruption. After the variable was processed, it is put into the SQL statement string.
while ($row = mysql_fetch_object($rs)) {
echo $row->Id;
echo " ";
echo $row->Name;
echo " ";
echo $row->Price;
echo "\n";
}
We fetch the data using the mysql_fetch_object() function. The function fetches a result row as an object. And we use the object notation to get the table columns.
$ php query3.php
Connection established
Database selected
Query: SELECT Id, Name, Price From Cars Where Name = 'Volkswagen' executed
8 Volkswagen 21600
The output of the example. We found the car and printed the whole row to the console.
Continue Reading