Jump to content


Check out our Community Blogs

chili5

Member Since 12 Mar 2008
Offline Last Active Dec 02 2017 05:41 PM
-----

#520555 Java Maps II

Posted by chili5 on 02 November 2009 - 03:14 AM

Map Views

In the last tutorial, we looked at creating maps. In this tutorial we are going to look at how to output maps. There are three different views that we might be interested in.

They are the keys, the values, and both the keys and the values.

First we need to create a map. Run this code:

Map<Integer, Integer> theMap = new LinkedHashMap<Integer, Integer>();
        int nKey, nValue;

        for (int i = 0; i < 5; i++) {
            nKey = (int)(Math.random()*50)+10;
            nValue = (int)(Math.random()*30)+20;
            theMap.put(nKey,nValue);
        }

This creates a random LinkedHashMap with 5 key-value pairs.

We can't explicity iterate the map but we can create set views that we can iterate through.

The three methods that we are interested in are:

  • Set keySet()
  • Collection values()
  • Set entrySet()

Each of these methods returns a Collection that we can iterate through. An important feature to note is that if the set is modified then the map is also modified. The values method returns a Collection and not a set becaues there might be multiple values where as a Set only allows unique items.

Key Set

Set<Integer> keys = theMap.keySet();

This function returns a set that maintains all of the keys. We can now get an iterator that allows us to look at each key. Since we are using a LinkedHashMap the items we will access our in insertion order. The first item added is the first item accessed with the iterator.

We can get an iterator like this:

Iterator<Integer> it = keys.iterator();

Now, it is simply a matter of using a loop with the hasNext and next methods to go through the keys. The hasNext method will return false when the iterator has looked at each item. The next method returns the current item being pointed at and then moves to the next item.

while (it.hasNext()) {
        System.out.println(it.next());
}

That is simply. In that loop you can do all the processing of the keys that you want. You could also change the key which would be reflected in the map.

Value Set

The values() method allows us to process the values associated with each key.

Example:

Collection<Integer> values = theMap.values();

This values method returns a list of all the values in the map. It has to be a list because a set wouldn't allow duplicate values. A map can have duplicate values.

Once again we can use an iterator to go through the values and see what they are.

Iterator<Integer> it = values.iterator();

        while (it.hasNext()) {
            System.out.println(it.next());
        }

This code is the exact same code as above. What you will get as output is all the values that are held in the map.

Example Output:

24
39
45
20
39


Entry Set

This is probably the more useful function. When you want to know what the value is and what key is associated with that value.

Perhaps, you want to know what word occurs with what frequency. Another useful situtation is you want to know what nodes a certain node is adjacent to in a graph. A map would be great for this.

Getting an Entry Set

The entrySet method returns a set holding Map.Entry objects. Each Map.Entry object contains a getKey method, a getValue method and a setValue method. Using the setValue method makes changes in the map. These changes are reflected in the map.


Set<Map.Entry<Integer,Integer>> entries = theMap.entrySet();

We now have a set that holds a bunch of Map.Entry objects. We can once again get an iterator to process the items in the set.

Iterator<Map.Entry<Integer,Integer>> it = entries.iterator();

while (it.hasNext()) {
            Map.Entry<Integer,Integer> next = it.next();
            System.out.println(next.getKey() + "->" + next.getValue());
 }

Very simple code. Notice though that we have to store the next entry in a temporary object. Why? Well if we call it.next().getKey() the iterator moves to the next item so we cannot call it.next().getValue().

The above concepts are very useful and apply to all types of maps.

Hope this helps!!
  • 1


#520548 Java Maps I

Posted by chili5 on 02 November 2009 - 02:43 AM

Maps

A map is a collection that maintains a mapping of a key to a value. The implementations of the Map interface are generic classes. This means that the key and the values must be objects.

One use of a map would be to keep track of how many words occur in a sentence.

There are three main implementations of the map class.

  • HashMap
  • Hashtable
  • LinkedHashMap
  • TreeMap


Creating a Map

When we create a map we must specify the type of map, and the type parameters of the key and the type parameter of the value.

Example:

Map<String, Integer> theMap = new HashMap<String, Integer>();

Notice how I declare the type as Map and not HashMap? This Map is an interface that is implemented by HashMap. This makes it much easier to change the implementation later.

I would just change HashMap to LinkedHashMap and the program would not break.

Example of creating a LinkedHashMap

Map<String, Integer> theMap = new LinkedHashMap<String, Integer>();

Differences Between Maps

The classes HashMap and Hashtable both implemented unordered maps. The big difference between the HashMap class and the Hashtable class is that the Hashtable class does not permit null keys and values. The HashMap class does.

A LinkedHashMap maintains items in insertion order. So when you iterate through the map, you will access items in the order that you added them to the map.

A TreeMap implements a SortedMap interface. This map maintains items in sorted order.

Adding Items

Despite what method you use to add items, the method is always the same to add items.

Object put(Object key, Object value)

You specify the key and the value that the key should be mapped to. The key might be the word and the value might be the number of times that key has occured.

theMap.put("James",new Integer(1));

Notice that you can only add each key once. If I try to add James again, it will just update the value previously associated with James.

Example:

theMap.put("James",new Integer(2));

James is now associated with a value of 2 not 1.

Removing Items

This is as simple as calling the remove function and passing the key that you want to remove.

Example:

theMap.remove("James");

Now, the program is free to add James as a key again. This function also returns the value that was associated with the key. So if James was associated with a 2, the return value would be an Integer object holding the value 2.

Otherwise, the program returns null.

Retrieving Values

This is as easy as using the get method and passing in the key. So if I want to know the frequency that James has occured at I would call this method:

theMap.get("James");

James is the key and the return value is the value associated with the key. In this case, the frequency that James has occured at.


Contains Key

If we want to check if a certain word has occured in the sentence, we would use the containsKey method. This method returns true if a certain key exists.

Example:

if (theMap.containsKey("James")) {
	System.out.println("James has occured in the sentence.");
}

There are more methods available to you, but these are the majority of the useful ones. We will look at iterating through the maps in the next tutorial. :)

Exercise

Create a word counter. The user will enter a sentence using standard input. The program will keep track of how many times each word occurs in a sentence.

Output all the words that occured and the frequency at which they occured.
  • 2


#520508 Java Sets 1

Posted by chili5 on 01 November 2009 - 06:01 PM

Java Using Sets

A set is a container that doesn't allow duplicate values.

In Java, there is three implementations of the set: TreeSet, HashSet, LinkedHashSet.

The difference is the TreeSet maintains items in sorted order, the HashSet doesn't maintain the items in any specific order. The LinkedHashSet maintains items in insertion order.All three Set classes implement the Set interface so it is easy to change the type of set used.

Creating a Set

TreeSet<Integer> v = new TreeSet<Integer>();

This code creates a new TreeSet that will only store integers.

Adding Items

v.add(5);
v.add(3);
v.add(2);
v.add(4);
v.add(5);

The add method adds an item to the set. After executing the above code the number of items is 4. The 5 is only added once. After executing v.add(5) a second time nothing happens.


Add All

You can add all elements in a collection to a set using the addAll method.

Example:

ArrayList<Integer> nums = new ArrayList();
for (int i=0;i<5;i++) nums.add(i);
v.addAll(nums);

Iterators

An iterator allows you to iterate and process the items in a set.

Iterator<Integer> it = v.iterator();

while (it.hasNext()) {
	System.out.println(it.next());
}

The next method moves a pointer to the next element in the set and outputs the previous item. The hasNext method will return false when the pointer is pointing after the last item.

Output:

2
3
4
5


Notice how the output is in sorted order? This is because we used a TreeSet which implements the SortedSet interface.

Removing All Items

This is a simply matter of calling the clear method. It removes all items in the set. Then the size will be set to zero.

Example:

v.clear();
System.out.println(v.size());

This is useful in contest programming when you want to reset the variables for the next set of input.

This is a quick introduction to sets. In the next tutorial we will look at the other methods in the set interface and converting between sets.
  • 1


#516782 JavaScript Dates - Get Methods

Posted by chili5 on 18 October 2009 - 02:24 AM

JavaScript Dates

The JavaScript language contains a very useful Date object for manipulating dates. With this object you can do all sorts of really fun and interesting things.

First we are going to look at how to get a Date object.

Try out this code:

<script language="javascript">
var theDate = new Date();
</script>

For those of you not familiar with the use of objects. The new keyword means to create a new instance of the Date object. This calls a special function known as the constructor to initialize the object. This constructor that we just used initializes a Date object with the current date.

Now let us display the date to the screen.

document.write(theDate);

When you run this code you get this result:

Sun Oct 18 2009 05:40:16 GMT-0700 (Pacific Daylight Time)


That is a lot of information that you may not always want. The date class provides methods for being more specific.

http://forum.codecal...=1&d=1255872136

The getHours method is very simple it gets the number of hours in the current date object. The getDay method returns the day of the week. The return value will be between 0 and 6 where 0 is Sunday and 6 is Saturday. Most of these methods are pretty self explanatory. One of them that might not make as much sense is the getTime method.

This method returns the number of milliseconds that have past since January 1st 1970 at midnight. This value refers to the UNIX epoch and hence is know as the UNIX timestamp. You may ask so what? What is the point? Well those who are familiar with PHP know that this is the most flexible method of working with dates.

If the user chooses a time, you can store the UNIX timestamp in the database and display it however you like. You can easily change how the date is displayed. You are not restricted to any format of date.

Displaying the Current Time

We are going to use the above methods to display the day of the week and the current time.

Example:

Sunday, October 18, 1992 5:57:05 AM


The first thing we need is to get all the information we need.

var nMonth = theDate.getMonth();
var nDate = theDate.getDate();
var nDay = theDate.getDay();
var nYear = theDate.getFullYear();
var nHours = theDate.getHours();
var nMinutes = theDate.getMinutes();
var nSeconds = theDate.getSeconds();

By using the methods in the date class we are almost done already. Besides displaying it we are done already. However, we know that nDate and nMonth hold integer values that represent a month. How are we going to convert these to strings?

Since January is 0, I think an array is good to use here.

var arsMonths = new Array();
arsMonths[0] = "January";
arsMonths[1] = "February";
arsMonths[2] = "March";
arsMonths[3] = "April";
arsMonths[4] = "May";
arsMonths[5] = "June";
arsMonths[6] = "July";
arsMonths[7] = "August";
arsMonths[8] = "September";
arsMonths[9] = "October";
arsMonths[10] = "November";
arsMonths[11] = "December";

Now notice how January is stored at index 0? This means that we get direct access to what the month actually is by using:

arsMonths[theDate.getMonth()];

We need something similar for the use of days.

var arsDays = new Array();
arsDays[0] = "Sunday";
arsDays[1] = "Monday";
arsDays[2] = "Tuesday";
arsDays[3] = "Wednesday";
arsDays[4] = "Thursday";
arsDays[5] = "Friday";
arsDays[6] = "Saturday";

We once again get direct access to what day it is by using:

arsDays[theDate.getDay()];

At this point it is simply a matter of using an output statement to display the date.

document.write(arsDays[nDay] + ", " + arsMonths[nMonth] + " " + nDate + ", " + nYear + " " + nHours + ":" + nMinutes + ":" + nSeconds);

When you run this code it should show:

Sunday, October 18, 2009 6:11:49


Now what if we want to display if it PM or AM? In a 12 hour clock system, we use PM and AM to show if the time is before or after noon. However you should note that all times are given in 24 hour time.

Changing to 12 hour time

To change to 12 hour time, we simply look if the hours are greater than 12, if they are we take away 12 and set a suffix to PM. Easy.

if (nHours > 12) {
	nHours -= 12;	
	sSuffix = "P.M.";
} else {
	sSuffix = "A.M.";
}

Now we simply display sSuffix at the very end.

document.write(arsDays[nDay] + ", " + arsMonths[nMonth] + " " + nDate + ", " + nYear + " " + nHours + ":" + nMinutes + ":" + nSeconds + " " + sSuffix);

Now consider if the time is 5:03:02. JavaScript is not going to display these leading zeroes for you. We have to check if we need them and add them ourselves. This is easy. We need a leading zero if minutes or seconds is less than 10.

if (nMinutes < 10) {
	nMinutes = "0" + nMinutes;	
}

if (nSeconds < 10) {
	nSeconds = "0" + nSeconds;	
}

That is all. I hope that you have seen that working with dates is fairly simple. You should know that there is more that you can do, but that is a topic for another day.

You can view the results here.

Attached Thumbnails

  • methods.JPG

  • 3


#513175 Variable Arguments

Posted by chili5 on 05 October 2009 - 02:17 PM

Java Variable Arguments

Java allows you to pass a variable number of arguments to a function. We specify several arguments with a variable type followed by an ellipise and a name. The variable number of arguments must come as the last parameter of the function.

Example:

public static int sum(int... nums) {
        int nSum = 0;

        for (int x=0;x<nums.length;x++) {
            nSum += nums[x];
        }
        return nSum;
    }

This function takes a variable number of arguments and returns the sum of all the arguments. The key here is that you treat the variable arguments as an array.

Use this code to test out the function:

System.out.println(sum(3,4,2,5));
System.out.println(sum(-1,2));
System.out.println(sum(9,3,5,3,2,3,4,3,2,3,2,1,9,-5));


There is also a foreach loop that you can use in the function.

public static int sum(int... nums) {
        int nSum = 0;

        for (int i: nums) {
            nSum += i;
        }
        return nSum;
    }

This code basically does the same thing as above. It assigns each item in the array of parameters to i and then increases the sum by i. They both do the same thing. However, I like the first loop better because it allows me to control where in the array I start and where in the array I stop.


Combining varargs with static arguments


You can use a variable list and static number of arguments. The key here is that the variable arguments list must be declared at the end of the parameter list.

E.g.

 public static int product(int n, int... nums) {
        int product = 1;

        for (int i=0;i<nums.length;i++) {
            product *= (nums[i]);
        }
        product *= n;
        return product;
    }

In this code the user must pass one integer and then as many integers as they want.

Example:

System.out.println(product(3, 4,2,5));

In this case, 3 is the integer that must be passed. The rest of the integers are optional.

E.g.

 System.out.println(product(3));

Hope this helps! Also it is nice to note that the same functionality exists in C and C++.
  • 3


#512971 Final Variables and Method Parameters

Posted by chili5 on 04 October 2009 - 03:12 PM

Final Variables and Method Parameters

A parameter to a function can be declared with the keyword final. This indicates that the parameter cannot be modified in the function. The final keyword can allow you to make a variable a constant.

You might want to pass an array but ensure that the method doesn't modify the array.

Example of using final:

public static void f(final int var) {
	System.out.println(var);
}

This method ensures that the user cannot modify var. If the user tries then an error occurs.

You can call this method just like any other method. The key here is that the var variable cannot be modified.

Let us try to modify the variable.

Change the function to:

public static void f(final int var) {
	System.out.println(var++);
}

If I try to compile this code and call this method then a RuntimeException is thrown. However, this might not be easy to find. You may accidentally modify the variable in the method without realizing it. The nice thing is Netbeans won't compile my program with this error.

It will just say:

final parameter var may not be assigned


However, it is worth to note that you can do this:

public static void f(final int var) {
     System.out.println(var+1);
}

This isn't modifying the variable.

Final Array

We can declare an array to be final. Let us take a look at what final does with an array.

public static void f(final int[] arr){
        arr[2]++;
}

Call the method with this code:

int[] arr = {3,2,5,4};

f(arr);

Do you think the program will compile, or will it throw a RuntimeException?

It actually will compile. The program isn't modifying the array. It is modifying an item in the array. However, trying to allocate a new array will throw an error.

E.g.


public static void f(final int[] arr){
     arr = new int[7];
}

This will throw the RuntimeException.

The final keyword is great if you want to ensure that you do not modify a variable when you pass it to a function. You can also use it with class variables. This is similar to using const in C++.

Final Variables

Similarly, a variable can be declared final. You can also declare classes as final (meaning that they cannot be extended).

Example:

public final int X = 5;

  • 2


#511993 Boolean Operators

Posted by chili5 on 01 October 2009 - 02:20 AM

Boolean Operators


The four boolean operators are:

! Logical Not
& Logical And
| Logical Or
^ Logical XOR


Not returns true if the operand is false and true otherwise.

Examples:

x = true
!x = false
!x = true
!(!x) = true

Logical AND Examples

The AND operand returns true if both operands are true.

x = false
y = false


x & y = false

x = y = true;
x & y = true;

x = false;
y = true;

The & operator when used on boolean expressions is an unconditional logical AND. If the first expression is false, it will still check the second expression. Where as the && operator is the conditional logical AND. As soon as one expression is false, it stops evaluating any other expressions.

Logical OR Examples

The operator for logical OR is a pipe (|). This operator returns true if one of the operands is true. Like the AND operation, this operator evaluates both expressions even if the first one returns false. Where as the || operator stops as soon as one of the expressions returns true.

Examples:

x = false;
s = true;

x | s = true;

This is true because s evaluates to true.

x = true;
s = true;

x | s = true;

This is true because one of the operands is true (they both are but only one of them has to be true).

x = false;
y = false;

x | y = false;

Both of them are false, so the return value here is false.

Logical XOR

This operator (^) returns true if and only if one of the operands is true.

E.g.

x = true;
y = false;

x ^ y = true;

In this case x is true and y is not. So the return value is true. If both operands are true then the return value will be false.

x = false;
y = false;
x ^ y = false;

In this situation both of the variables are false, so the return value is false.

Likewise this code below is also false:

x = true;
y = true;
x ^ y = false;

Words of Caution

You have to be careful using this operators. In some cases they are treated as bit operators not boolean operators. These are treated as bit operators when they are used on numeric data types.

E.g.

5 | 2

is not a boolean operation. It is a bit wise OR.

If you are using the & and | operators you might want to consider using the && and || operators. There is a difference and in some cases this difference may be crucial.
  • 2


#511269 Help with JOptionPane showMessageDialog

Posted by chili5 on 27 September 2009 - 03:52 PM

Of course, why wouldn't it be?

JOptionPane.showMessageDialog(null,"Hi " + sName + "\n\rEnter your password.");

  • -1


#506395 Flash: Arrays and Vectors

Posted by chili5 on 06 September 2009 - 08:59 AM

Flash Arrays and Vectors

Both arrays and vectors are structures that provide fast 0(1) access to any item in the array. They are direct-access containers. If you are familiar with arrays in other languages they are a bit different in ActionScript.

In C++, we create an array that is a fixed length structure. It also has a type. So we create an array of say size 5 to hold ints. It can only hold integers. A course in data structures shows that an array has serious problems where the programmer doesn't know the size of the data available. This leads to the vector class in the STL.

ActionScript doesn't introduce these limitations. The array is not a typed structure. It also is not limited by a size. This introduces problems when we constantly re-size the array. As of this writing, there is no linked structures in ActionScript. If you need a linked list, you will have to implement it yourself. I can imagine that in a future release, ActionScript will have some equivalent of the STL.

Using arrays

Creating an array

var arnNums:Array = new Array();

This creates an empty array. It can hold any type of data you want. Integers, floats, strings, anything.

To add an item to the end of the array, we use the push function.

arnNums.push(5);

The array is now this:

5


Using push again allows us to see that it adds an item to the end. We will this time add a string.

arnNums.push("j");

The array is now:

5 j


Removing an item is as simple as calling the pop method.

Example:

arnNums.pop();

This removes an item from the end of the array.

The array is now:

5


Outputting an array

There are two ways to output the array to the output window. One is to trace the entire array. This prints the array out item by item separated by commas.

Example:

trace(arnNums);

Output:

5, 3


The other way is to use a loop to output individual items.

Example:

for (var i=0;i<arnNums.length;i++) {
         trace(arnNums[i]);
}

Output:

5
3


Sorting

This is as simple as calling the arrays sort method.

Example:

arnNums.sort();
trace(arnNums);

The array is now:

3, 5


Using Vectors

The only difference between arrays and vectors, is that the vector is a typed array. This is done with the concepts of generics. This is the only generic class that exists so far, and you can't make your own generic classes yet. I imagine that this will change in a future release. I don't imagine ActionScript becoming like C++ but more like Java. At least syntactically, it won't let you do things that you can in C++. Meaning, no pointers, and other things like that. Flash will still remain easy to use for animations (where as Java is not). This language is more like JavaScript syntactically but I can imagine it becoming more like Java.

I am just going to show you how to create a vector. All the methods work in the exact same way as the array.

Creating a Vector

var vNums:Vector.<int> = new Vector.<int>();

The things in the angle brackets you just have to change for the type of data that you want.

Some more vectors:

var vWords:Vector.<String> = new Vector.<String>();
var vPeople:Vector.<People> = new Vector.<People>();

The last example is assuming that a People class exists. This class works the exact same as the array. Why? Simple, it is one. Just the compiler ensures that you add data of a defined type to the structure. If you try to add data of a different type, a default value of the predefined type is added.

These vectors are very useful in drawing complicated objects.
  • 2


#506345 Flash: More Advanced Drawing

Posted by chili5 on 06 September 2009 - 04:22 AM

Flash - Drawing Advanced Graphics


Previously, we looked at how to draw basic graphics. This involved setting a line style, then command by command (with lineTo and other methods) drawing your shapes. There are more methods that alllow you to do more complicated drawings.

These methods require you to set all properties like coordinates and fill colors as we did before with graphics.beginFill. Then a single drawing method is used to process the data and draw the shape.

The Graphics.drawPath methods take 2 vectors and a string as parameters. The first vector holds integers between 0-5 that indicate a certain command is to be used.

Each number between 0-5 represents a certain command. For example, 2 is lineTo, 1 is moveTo. You provide the constants in the order that with the simpler methods, you would have called the appropriate method in.

You put all your constants in a vector, and pass the vector as the first parameter to a draw method.

We then need a second vector to hold the parameters for the appropriate method. We will call this vector "data". Every 2 items in the data vector represents one x/y coordinate and is associated with one item in the commands vector.

Vector



A brief note that a vector is just a typed array. In ActionScript, the array structure is what C++ and Java programmers know as a vector. It has the ability to grow as we need it to. The difference being an array structure can hold any data type you want. The vector is a typed array. Meaning it can only hold one data type.


The third parameter of drawPath is a string. We won't worry about this for now. However, it is used to determine how to fill intersecting portions of the shapes. This could prove to be very useful for gradient fills.

Now enough talking let us look at some code, that draws a rectangle. First we will see a line style using graphics.lineStyle.

var commands:Vector.<int>  = new Vector.<int>();
var coordinates:Vector.<Number> = new Vector.<Number>();

graphics.beginFill(0x666699);

// first we have to moveTo the start location
commands.push(1); // 1 is the move to command
commands.push(2); // 2 is the lineTo command
commands.push(2,2,2,2);

// the start of the line is (5,50)
coordinates.push(5);
coordinates.push(50);
// draw a line from (5,50) to (5,100)
coordinates.push(5);
coordinates.push(100);
// draw a line from (5,100) to (200,100)
coordinates.push(200,100);
coordinates.push(200,50);
coordinates.push(5,50);

graphics.drawPath(commands,coordinates);

We load the commands vector with constants that indicate what command we want. The first command we push is 1. The drawPath method then takes as many values as it needs from the front of the coordinates vector and uses those as parameters for the moveTo function. Then we have a series of line functions.

The first two values we push to the vector are the start coordinates of our shape. Then the next values (in pairs of two's) indicate x and y values that we should draw a line to. This allows us to make a rectangle.

The resulting movie clip looks like this:

http://forum.codecal...=1&d=1252250247

I like to define my shape line at a time with several push statements but you can combine them into one push statement. This API allows you to make your program a lot shorter.

Later, we will look at the other constants that are available for you to use. Let us do something a bit more interesting with this though.

var commands:Vector.<int>  = new Vector.<int>();
var coordinates:Vector.<Number> = new Vector.<Number>();

graphics.beginFill(0x666699);
graphics.lineStyle(2,0x000000);

// first we have to moveTo the start location
commands.push(1,2,2,2,2,2,2);

coordinates.push(170,60,170,160,250,160,300,120,230,130,200,20,190,140);

graphics.drawPath(commands,coordinates);

The commands vector holds a bunch of calls for lineTo. The first method however is a moveTo method. The first two parameters indicate where we are moving to. So we start drawing at coordinates (170,60). Then the rest of the pairs are (x,y) indicate where we are going to draw to.

So the first line is from (170,60) to (170,160).

The above code results in this drawing:

http://forum.codecal...=1&d=1252250247

You can start to see how this API makes life a whole lot easier. However, this is just the surface. We can do a whole lot more.

Other Classes



There are a lot of other classes you can use including IGraphicsData, GraphicsEndFill, GraphicsStroke and a few more. We will look at these classes another day. If we looked at them now, then this would be a lot of info at once, and be impossible for anyone to stay interested.

Attached Thumbnails

  • Rect.JPG
  • draw2.JPG

  • 2


#505918 PHP Variables and Variable Functions

Posted by chili5 on 04 September 2009 - 05:57 AM

PHP Variables

In PHP, variable names are case-sensitive. These variables: $test, $Test, $TEST, $tesT all are different variables. Unlike C languages, you do not have to declare a variable before you use it. If you use a variable that you have not created in a script, then PHP will just create a new variable for you. This may make it harder to find your error.

Creating a variable

PHP variables start with a dollar sign. The first character must be a letter. Other than that, you can use any letter or number. The variable name can be as long and as short as you want.

Examples:

$text = "test";
$text = 5;

Another thing to note, is that you can change the type of variable. This differs from Java and C++. This can also cause a source of error if you are not careful. First the $text variable was a string variable, and then it becomes an integer variable.

Constants

A constant variable is a variable that once defined, can never be changed. I like to put all my constants in strict upper case. This makes it easier to find. A useful example of constants is database access information.

Once this information is set, you wouldn't want to change it.

We create constants using the define function.

Examples:

define("DB_HOST","localhost");
define("DB_USER","root");
define("DB_PASS","pass");

The first parameter is the name of the constant. The second parameter is the value of the parameter. So I could connect to a database like this:

mysql_connect(DB_HOST,DB_USER,DB_PASS);

You can use them just like any other variable. The only thing is you can't change them.

If I try to change the variable, I get an error.

Example:

DB_HOST = "Test";

The error I get is:

Parse error: parse error in C:\wamp\www\PHP\constants.php on line 54


This is more than useless because I don't have errors set very well in my php.ini file. All I know is that I have an error on line 54. This is referring to where I try to change the value of the constant.

The third optional parameter allows me to specify if the constant is case sensitive or not. By default DB_HOST and db_host are the same constants. If I pass false as the third parameter, this makes DB_HOST and db_host both two different constants.

Example:

define("DB_HOST2","localhost",false);

echo DB_HOST2 . " " . db_host2

When I run this code, I get this warning:

Notice: Use of undefined constant db_host2 - assumed 'db_host2' in C:\wamp\www\PHP\constants.php on line 56


You don't have to pass true. The function assumes a default value of true, if you don't pass a third argument.

Checking Variable Type

PHP provides method is_int, is_string, is_array and so on for you to assess what type of data a variable is holding currently. Note that at one point in the string is_int can return true, and return false later. Variable types can change.

Example:

$x = "test";
$y = 5.5;
$b = false;
$test = 5;

if (is_int($x)) {
	echo "$$x is an int.<br />\n";	
} else {
	echo "$$x is a " . gettype($x) . "<br />\n";	
}

This code tests the what type of data $x is holding. I use two $ signs as to avoid printing the content of the variable. The gettype method returns the type of the data.

So this code outputs:

$x is a string.


So if tested $x with is_string, the method is_string would return true.


Isset, unset and empty

The isset method returns true if the variable has been set. This is similar to the empty function but they are not the same. The empty function returns true if a variable has not been assigned a value or has a false value. PHP considers "" (empty string), false, and 0 to be empty. Even though the variable has been assigned a value.

Example:

$x = 0;
	
if (empty($x)) {
	echo "Empty.";	
} else {
	echo "Not empty.";	
}

Output:

Empty.


However, even with a false value, isset will return true. This function simply checks if the variable has a value.

Example:

$x = 0;
	
if (isset($x)) {
	echo "Set.";	
} else {
	echo "Not set.";	
}

Output:

Set.


The unset function removes a variable, so that isset will return false.

Example:

unset($x);
if (isset($x)) {
	echo "Set.";	
} else {
	echo "Not set.";	
}

Output:

Not set.


  • 1


#505892 SQL Date Functions

Posted by chili5 on 04 September 2009 - 03:10 AM

SQL Date Functions

One thing you can do with dates is use the UNIX_TIMESTAMP function and the BETWEEN clause to determine if a date lies between two dates. However, there is a lot more that you can do.


Getting Current Date and Time

SQL provides us with a function NOW that returns the date and time.

Example:

SELECT NOW();

Output:

2009-09-04 06:25:27


You could easily store this value in a datetime field. You might use this in a registration script to record the date and time that someone registered on a website.


Getting Current Date

You might just be interested in the current date. SQL provides us with a function CURDATE that returns the current date.

Example:

SELECT CURDATE();

Output:

2009-09-04


Getting Current Time

The function CURTIME returns the current time. However, this might not be as accurate as you want because you are using the time on the database server. If getting the exact time the user did something is important, then the program should get the time value and pass that to the database.

Example:

SELECT CURTIME();

Output:

06:31:59



Adding Days

One thing that is really interesting about dates, is we can do all sorts of math to manipulate them. Consider the ADDDATE function which takes a date and adds x days to it.

Example:

SELECT ADDDATE(CURDATE(),30);

This code is going to add 30 days to the current date.

Output:

2009-10-04


You might use these functions in correlation with the IF function to determine if the user is allowed to do something. Say you only want people to post to your bulletin board if they have been registered for 30 days. Granted, this is something that the application should do. Not, something the database should do, but the database could do this for you.

Example:

SELECT IF(UNIX_TIMESTAMP('2009-04-32')>=UNIX_TIMESTAMP(ADDDATE('2005-04-32',30)),"yes","no");

If the date we passed in is greater than or equal to the registration date + 30 dates then the user is allowed to do something, and we return "yes". Otherwise, we return no.

Output:

No


Date Diff - Subtracting Dates

We can use the DATEDIFF function to subtract two dates. This function returns the number of days between the two dates.

Example:

SELECT DATEDIFF(NOW(),ADDDATE(NOW(),30));

I chose this example because it is easy to determine what the result is. Since I am finding the number of days between two dates, I chose two dates that are 30 days apart.

This SQL function is going to evaluate:

NOW()-ADDDATE(NOW(),30));

Thus the result should be -30. Now, let us run our code and see what happens.

Output:

-30


Formatting Dates

This function is a monster, it is very similar to the date function in PHP and works much in the same way.

The function prototype is:

DATE_FORMAT(date,format)

The format parameter is made up of different specifies that indicate how you want the date to be displayed.

Example:

SELECT DATE_FORMAT(NOW(),'%W %M %e, %Y %T');

This function is going to return the string formatted with a date and a time.

Output:

Friday September 4, 2009 06:50:01


Instead of memorizing all the specificiers, you are going to save a lot more time if you just look them up as you need them.

Make Time Function

This function returns a time value that is calculated from the parameters. It accepts three parameters, hour, minute and second.

Example:

SELECT MAKETIME(9,30,05);

Output:

9:30:05


Formatting Time Values

There is a function TIME_FORMAT that works much like DATE_FORMAT. It takes two parameters time and format. However the only format specifies you can use are ones for hours, minutes, seconds and microseconds. If you use any other specifies the return value will either be NULL or 0.

Example:

SELECT TIME_FORMAT(CURTIME(),'%I:%i:%S %p');

Output:

07:06:24 AM


  • 3


#505637 SQL Decision Structures

Posted by chili5 on 03 September 2009 - 11:24 AM

SQL Decision Structures

If you have programmed before, then these will be familiar. The two control structures available are: CASE and IF.

If... Else

These functions return a value depending on whether a condition is true or not.

Think of it like this:

if ((x == x) == true) {
	return "X"
} else {
	// false
	return "Y";
}

The generic syntax for this function is:

IF (expr,val1,val2)

The expression that we are testing is the first parameter. If expr is true, then the return value is val, otherwise the return value is val2.

Example:

SELECT IF(5>2,'a',4)

If 5 is greater than 2, the return value is 'a'. If 5 is less than 2 the return value is 4. Since 5 is greater than 2, the return value is 'a'.

Another example:

SELECT IF(3>4,'greater','less')

Result:

less


You can nest if structures by including an if structure as one of the return values. If you have used Excel before then this notation will be familar to you. You can make more complicated statements using AND and or operators.

This might be useful when you want to return data from one table, if a certain condition is true or from a different table if the condition is false.

Switch Case

The switch case structure is a concise method of testing one variable against multiple values.

The generic syntax is:

SELECT CASE value WHEN compareValue THEN result WHEN compare2 THEN result ELSE result END;

Example:

SELECT CASE 1 WHEN 5 THEN '5' WHEN 4 THEN '4' WHEN 3 THEN '3' ELSE 1 END;

Output:

1


This is a useless example but you might want to test a value that the user has entered and return a certain value depending on what the value is, or insert it into a different table depending on the value.
  • 2


#505510 SQL INSERT Queries

Posted by chili5 on 03 September 2009 - 05:55 AM

SQL INSERT Queries

We use SQL insert queries to add data into tables. There are two forms of this command. One where we specify the columns we want to insert into and the other where we don't specify what columns to insert into.

If we don't specify what columns to insert into, we are inserting into all columns. I like to always specify what columns I am using. Note, if you specify four columns to insert into, but only provide 3 values then you will get an error.

Let us use this table here to demonstrate insert queries:

CREATE TABLE IF NOT EXISTS `people` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `date` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

All columns

The generic syntax for inserting into all columns is:

INSERT INTO table VALUES('one','two','three'....)

Integer values aren't in single quotes but everything else should be in single quotes.

Example:

INSERT INTO people VALUES(7,'joey','2009-04-07');

This is going to insert one record into the table. The id number is 7, the name is 'joey' and the date is 2009-04-07.

Specifying the Columns

One reason, we might want to do this is so we can use an auto increment field that populates itself.

Example:

INSERT INTO people (name,date) VALUES('black','2009-04-22')

After we name the table in parenthesis we specify the name of the columns we want to insert into. They are not in quotes. They are separated by a comma also. Then we specify the values for each column. Since we specified to use 2 columns we must specify 2 values to use.

The id field is auto incremented so it will populate itself.

Incorrect Number of Values

If we specify 2 columns and provide more or less than 2 values then we will see an error.

Example:

INSERT INTO people (name) VALUES('black','2009-04-22')

Output:

#1136 - Column count doesn't match value count at row 1


This occurs because there is a value specified that MySQL has no idea what to do with.

Securing Data

These queries are very often used to insert data from the user into a database. However, allowing the user to input data into the database can be very insecure at times. If the user decides to enter a single quote, they can stop the query, then enter there own query which will be executed by the database server.

If the query looks like this:

INSERT INTO people (name) VALUES('$num')

Then the user enters this:

nam');DROP DATA BASE test; )#

that is populated into $num and this query is executed:

INSERT INTO people (name) VALUES('nam');DROP DATA BASE test; )#');

The single quote that the user entered signals the end of the value then a close parenthesis and semi-colon indicates the end of the query. At this point the INSERT query is valid and I can send another query to do whatever I want. When I am done, I simply use # to comment the rest which allows my bad query to run.

The database server can wrap the value with a call to QUOTE around the inputted values which will secure the input from this kind of attack.

It changes ' to \' which escapes the single quote and prevents it from ending the query. I still believe that this is something the application should do. Why should we even send bad data to the database in the first place?
  • 2


#505492 SQL: Like and Not Like

Posted by chili5 on 03 September 2009 - 05:27 AM

SQL Like and Not Like

Using Regular Expressions allows you to select data that matches a certain format (or perhaps data that does not match a format). For this we use the LIKE and NOT LIKE clauses.

The first thing we are going to do is create a people table that we can use to play around with.


CREATE TABLE IF NOT EXISTS `people` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `date` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

INSERT INTO `people` (`id`, `name`, `date`) VALUES
(1, 'James', '2009-09-16'),
(2, 'Joe', '2009-09-30'),
(3, 'Jack', '2009-09-18'),
(4, 'Bob', '2009-09-17'),
(5, 'Tiik', '2004-09-16');

The table has three fields, id, name, and date. We can use regular expressions to find all customers who have not registered in 2009 for example. We can also use it fo find all names that start with "J" or end with "k".

I use these functions a lot. They are very useful for implementing searches in programs.

LIKE clause

Let us first select all the names of people who start with J.

We use % to indicate to match any string of any length.

So:

'J%' means to match any string that starts with "J" and followed by a string of any length.

Try this:

SELECT name FROM people WHERE name LIKE 'J%'

Return values:

James
Joe
Jack


Now using the same % wildcard, we are going to display all names that end with 'k'.

Instead of putting the % wildcard at the end of the pattern, we are going to put it at the beginning. This means to find all strings that string art with any characters (of any length) and end with k.

Example:

SELECT name FROM people WHERE name LIKE '%k'

Output:

Jack
Tiik


This code lets us find all values that end with characters.


NOT LIKE

We use NOT LIKE to find things that do not match a certain pattern. We are going to find all strings that do not start with a j.

Try out this code:

SELECT name FROM people WHERE name NOT LIKE 'j%'

Output:

Bob
Tiik


These two "functions" are really helpful for implementing searches. I use them a lot in my program when I use searches of database.

Other wildcard available are:

_ to match any character. This can be useful for locating something when you know part of it but you don't know all of it.

Say you want to find a phone number but you only know the first 2 digits, you can write a query like this:

SELECT * FROM contacts WHERE phone_number LIKE '51_-___-____'. 

This will return things like:

515-111-1111
512-134-abcd


Anything that is in the format of a phone number.

This is very simple, but is VERY useful. Next, we will look at using REGEXP for even more control.
  • 1




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download