April 13th, 2009 | Tags: ,

OK, first of all, make sure your host supports a recent version of PHP & MySQL. It’s generally better to use a special connection file, separate from your coding file, so if someone succeeds to hack into the main file, he won’t get the database info.

To be able to connect to any database, the database needs to exist, so after you create a new database, you’ll need to attach a username to that database, and then connect via that username [and password].

So lets create a new file, called connect.php

<?php

// Define connection variables...
$c_username = "database_username";
$c_password = "password";
$c_host = "localhost";
$c_database = "database_name";

// Lets actually connect.
$connection = mysql_connect($c_host, $c_username, $c_password)
or die (
"It seems this site's database isn't responding.");

mysql_select_db($c_database)
or die (
"It seems this site's database isn't responding.");

?>

Of course you’ll need to edit the variables in the code snippet for it to work.

After that, all you need to do is include that file to be connected, like so:

<?php

// Include the connection file.
include("connect.php");

?>

Thats about it, after connection, you can query the database as you like.

April 13th, 2009 | Tags:

Before getting started, I’ll assume you already read the Database Connection tutorial and know how to connect & select the database of your choose.

Retrieving data from a database is a common task for web database applications, the most common use is to display the data in a web page.

To get the data from the database, we’ll need to use the SELECT command.

OK, lets say we have a table named “pets”, containing pets names, types…etc

We want to display all the dogs within our page. Pay attention to the code comments.

<?php

// we'll select all the information in the database for five dogs.
$query = "SELECT * FROM pets
WHERE type = 'dog'
LIMIT 5"
;

// actually execute the query.
$result = mysql_query($query);

?>

Now that we got the information, we’ll need to display it:

<?php

// for every dog we selected, run the following block.
while ($row = mysql_fetch_array($result))
{
// display information for each dog.
echo "Name: $row[name], Age: $row[age], Breed: $row[breed] ";
}

?>

We’ve retrieved the data and displayed it. Of course you should make nicer, but you get the idea.

You can see the full script below:

<html>
<head>
<title>Dogs</title>
</head>
<body>

<?php

// connect to database.
include("connect.php");

// we'll select all the information in the database for five dogs.
$query = "SELECT * FROM pets
WHERE type = 'dog'
LIMIT 5"
;

// actually "do" the query.
$result = mysql_query($query);

// for every dog we selected, run the following block.
while ($row = mysql_fetch_array($result))
{
// display information for each dog.
echo "Name: $row[name], Age: $row[age], Breed: $row[breed] ";
}

?>

</body>
</html>

April 13th, 2009 | Tags:

To send emails using PHP, we’ll be using the mail() function.

The following is an example you can use to send emails.

<?php

// define email settings...
$to = "user@domain.com";
$subject = "Test Email Subject";
$message = "This is a test email message";

// Shorten lines longer then 50 characters.
$message = wordwrap($message, 50);

// send email.
mail($to, $subject, $message);

?>

April 13th, 2009 | Tags:

Functions are used to re-use code. When you are using the same block of code over and over, just create a function, and when you want to update something, you’ll only need to update it once.

The basic syntax is like this:

<?php

function functionname($param1, $param2, $param3)
{

return;
}

The return is inserted at the end to make sure the function will close.

Lets look at a small example, shall we?

Lets say you want to display the recent news, on each page of your site.

<?php

function recentNews()
{
echo
'
<b>Recent News</b>
<p>John Doe is missing again!</p>'
;
}

?>

Now just add the following function call on every page:

<?php

recentNews

();

?>

Whenever you want to add/modify/remove any news, just change it within the function, and it’ll update everywhere.

Keep in mind when you want to call the function, the function definition must be included into that page.

April 13th, 2009 | Tags:

Lets say we have the following HTML form, simple enough, right?

<html>
<head>
<title>Using forms with PHP</title>
</head>
<body>
<form action="submit.php" method="post">
Name: <input type="text" name="name" size="25" />
<input type="submit" value="Submit!" />
</form>
</body>
</html>

Notice the attributes within the tag, the action part is telling the form to go to submit.php after the form is submitted, the method part is just defining the form type [post or get].

So now that we have that page, we need the submit.php page.

Once the form is submitted, it executes submit.php. The form input we are using is called “name”. After the form is submitted, we can access that variable with $_POST[‘name’].

<?php
/* File name: submit.php */

// store & clean the form variable.

$name = trim(strip_tags($_POST['name']));

// now we can play with it.
echo 'Hello world, my name is <b>' .$name. '</b> and I love SweDesignz!';

?>

As you can see above, we are using the submitted name in our script. You can do some more cool things. For example instead of entering a name, you can submit a number, and then play around with it.

This was just to show you how to use the form variables in your script.

April 13th, 2009 | Tags:

You may have seen this feature of some sites around the net. Time execution basically means you can see how long it took for the page to load. This can be helpful when programming, or whenever.

An example of this script:
Script Execution Time: 0.001 seconds

Lets say you have a basic HTML page:

Just some text Just some text Just some text
Just some text Just some text Just some text
Just some text Just some text Just some text
Just some text Just some text Just some text
Just some text Just some text Just some text

So we’ll add the time execution script here.

The basic logic behind this is we need to see at what time the script started, and when it ended. After that we just need to find the difference between those two numbers.

To refresh your memory on how time and dates on the internet work, please check out, Playing with Dates.

Instead of using the common mktime() function to get the current timestamp, we’ll use the following function to get the micro time. This is because usual execution times are much less then 1 second, so we’ll need to use this for more accurate times.

The function we will be using to get the current micro time is this:

<?php
// Function to calculate script execution time.
{
list (
$msec, $sec) = explode(' ', microtime());
$microtime = (float)$msec + (float)$sec;
return
$microtime;
}
?>

So once we have that, we’ll need to implement this within our HTML page.

<?php

// Function to calculate script execution time.
function microtime_float ()
{
list (
$msec, $sec) = explode(' ', microtime());
$microtime = (float)$msec + (float)$sec;
return
$microtime;
}

// Get starting time.
$start = microtime_float();

?>

Just some text Just some text Just some text
Just some text Just some text Just some text
Just some text Just some text Just some text
Just some text Just some text Just some text
Just some text Just some text Just some text

<?php

$end

= microtime_float();

// Print results.
echo 'Script Execution Time: ' . round($end - $start, 3) . ' seconds';

?>

That’s about it, now you can see how long it takes to load the page.

*NOTE* you can change the accuracy of the time by changing the last parameter in the round() function. We use 3 [which means 3 numbers after the dot] but you can change that as you wish.

April 13th, 2009 | Tags:

Everyone knows of the HelloWorld Application no?

Well in Java, it is as simple as this.

public class HelloWorld undefined

Ok in the class part:

public class HelloWorld

We are stating that we are to create a new class called HelloWorld. The public part means that this class is available to any other class. You will get familiar with public, final, and different kinds of modifiers as you get more into methods.

System.out.println("Hello World!");

This means that we are sending a message to the screen. The System.out.println defines this. It will send whatever is in quotes to the screen. SO in this case, you will see
Hello World!
Every ending statement also ends with a semicolon ‘;’

When you save this program, you should save it exactly as the class name. In this case, we named our class HelloWorld. SO when you save this file, you MUST save it as HelloWorld.java . Now when you compile this program it creates a .class file of our class. So in this case it would create – HelloWorld.class. A dot class file is pretty much the computer’s way of understanding what we type!

April 13th, 2009 | Tags:

Ok, now that we have a little feel of what a java program consists of, and how to print some text on the screen. We shall experiment with variables.

public class Variables undefined

Ok, by now your thinking, “Thats a doozy” or maybe you are thinking “How dumb does this guy think I am?”

int myInteger;
double myDouble;

These 2 lines mean that we are declaring (NOT INITIALIZING!) two variables. One of the variables is an int, the other a double [int = number; double = long number]

The name’s of the int is myInteger. The name of the double is myDouble. int, and double are called data types. They store certain kinds of data. Int variables hold variables with no decimals. Doubles hold whole numbers and decimals.

You can Google aata types and java to find out more of the data types. We will be working mainly with ints and doubles.

myInteger = 34;
myDouble = 23.32;

In these two lines we INITIALIZE the variables, setting them equal to numbers. Notice all of our statements end with simicolons. Note that if you would have done something like
myInteger = 34.1, this would bring up a compile error.
myDouble = 2, this would not bring up a compile error.

System.out.println("myInteger");    //This is a comment.
System.out.println(myInteger);    //Comments are ignored

In this line, we are going to print myInteger. Notice in the first line there are quotes around our variables. In the first case, it would print:
myInteger

But in the second case it would print:
34

This is because quotes print whatever you put inside of them. (there are a few exceptions)

The same thing goes for

System.out.println(myDouble);
System.out.println("myDouble");

Ok, now this line of code is a bit trickier:

System.out.println("My Numbers Added " + myInteger + myDouble); //prints 3423.32
System.out.println(myInteger + myDouble + " My Numbers Added");   //prints 57.32

In the first println, it will print 3423.32. This is because there is a string literal before our variables. The compiler thinks of these as strings, and just attaches them, one after another. Though in the second case, the variables come first, thus they are added together.

To fix the first one, we would have to put paranthesis around what we want added. Thus we’d use:

System.out.println("My Numbers Added " + (myInteger + myDouble));
April 13th, 2009 | Tags:

For this demonstration you will need the cs1 package.

You can get that from:
http://www.cs.bilkent.edu.tr/~david/cs101/RevisedCS1Package/cs1.jar

Big big thanks for the creators of this great package.

With the keyboard package, we can take data entered from the user.

import cs1.Keyboard        //This imports the Keyboard class from
//the cs1 package.

public class UserVariables undefined

This class file is pretty straight forward. We declared 2 ints, 1 double, and 1 String. Strings are new to us. Strings hold letters and numbers, but they hold numbers differently. You cannot add the numbers together. So you can’t add a string that holds “1” and “2” and expect 3. You can add strings to other strings, but they won’t mathematically add.

In the first and second println, we ask for some numbers. The numbers the user types in, will be stored according to their variables. So the first number is stored in num1, and the second into num2. I will explain the Keyboard.readDataType() later.

We can enter a double in our 3rd println, and it is stored into num3.

And on our final println, we can enter a string, which is stored in name. In the last 4 printlns, we are just printing what is stored in each variable.

Now, let’s continue:

Keyboard.readInt();
Keyboard.readDouble();
Keyboard.readString();

Pretty much anytime you see a (.) dot and paranthesis, you are working with a method.

The ‘Keyboard’ part means that you are using a method from the Keyboard class. The ‘readInt()’ is a method inside of the Keyboard class.
(Notice that most class files begin with capital letters and that when naming variables, the first word is usally lowercase, while the remaining have capital first letters.
Ex: myVariableIsLong, thisIsMyHouse, helloYou, etc)

Same thing for double and string.
‘readDouble’ is a method inside of the keyboard class.
‘readString’ is a method inside of the keyboard class.

The difference between these three is that the readInt method only reads integer variables typed from the user. (Otherwise compile error)
The readDouble method only reads doubles, or ints as doubles.
Ex: User types 1, and this becomes 1.0 The readString method only reads String type data. Of course you can enter numbers, but dont expect to mathematically work with them.

That is pretty much the cs1 package in a nutshell.

April 13th, 2009 | Tags:

Some of you may want to know about creating methods in java. I went threw weeks of studying and finally found out, or really understand how methods work and how to create them.

Lets start off with a regular class called Course.java Here is my code for this class:

public class Course {

public static void main (String[] args) {

Course course1 = new Course("ComputerScience", 1, 100.0);
Course course2 = new Course("English", 2, 76.0);
Course course3 = new Course("PE", 3, 96.0);

course1.ridPoints(12.2, 100.0);
System.out.println(course1);

course2.addPoints(2.0, 76.0);
System.out.println(course2);

course3.addPoints(3.0, 96.0);
System.out.println(course3);

System.out.println(course3.courseName());
System.out.println(course2.grade());

}
}

Ok, now you may wonder, WTF is this new method addPoints and ridPoints??? Well, I am using my objects (course1,2,3) and implementing my methods on them.

Course course1 = new Course("ComputerScience", 1, 100.0);
Course course2 = new Course("English", 2, 76.0);
Course course3 = new Course("PE", 3, 96.0);

This creates 3 courses for me to play with. Inside of each object’s parenthesis, there are 3 different things that define it. It’s Name, its Period, and its Current Grade.

course1.ridPoints(12.2, 100.0);
System.out.println(course1);

course2.addPoints(2.0, 76.0);
System.out.println(course2);

These 2 pretty much work alike, except in the first one, It gets rid of 12.2 points from a score of 100.0, and the value is stored in course1.

In the second one, we add 2.0 points to 76, and is stored in course2.

Now, of course we can’t just make methods and have no background information right? Hell yea thats right.

Here is the method code:

public class Course {

private int period;
private double grade;
private String courseName;

//Set up a course, period, and grade
public Course (String nameOfCourse, int periodOfCourse, double gradeofCourse) {
courseName = nameOfCourse;
period = periodOfCourse;
grade = gradeofCourse;
}

public String courseName() {
return courseName;
}

public int period() {
return period;
}

public double grade(){
return grade;
}
public double addPoints (double pointsAdded, double originalPoints) {
grade = pointsAdded + originalPoints;
return grade;
}

public double ridPoints (double pointsRidded, double originalPoints) {
grade = originalPoints - pointsRidded;
return grade;
}

public String toString(){
return (courseName + "\t\tPeriod= " + period + "\tGrade= " + grade);
}
}

Lets start with our simple methods such as:

public double ridPoints (double pointsRidded, double originalPoints) {
grade = originalPoints - pointsRidded;
return grade;
}

Here we know that this will be public, and will return double values, and this method’s name is ridPoints. Inside the paranthesis, is the data we have to type in order for any calculations to occur.

So now we can just add our objects name a (dot) and then out method.
Example : course1.ridPoints(12.0, 80.0);

The more simple methods like:


public int period() {
return period;

These just return the periods/grades/names of our objects. For instance we can try this: System.out.println(“Course 1 Period: ” + course1.period)

and this wil be printed

Course 1 Period: 1

public Course (String nameOfCourse, int periodOfCourse, double gradeofCourse) {
courseName = nameOfCourse;
period = periodOfCourse;
grade = gradeofCourse;
}

This declares what will be inside of our objects values.
Notice it’s name is the same as its class.

private int period;
private double grade;
private String courseName;

These private variables tell us, and the compiler that the only person/thing in the world that can modify them, is anything in the Course class.

In simpler terms, we can create a WhyAmIFailing.java file, and use our course.java methods.

But inside of our WhyAmIFailing.java, we cannot change any of the private values.

If these would have been declared public, you could have. Though this is not safe, and should not become a habit.

Good luck.