Test

Powered by Blogger.

Sunday 22 April 2012

php datatypes

PHP consists of 4 basic data types:
boolean - a boolean is actually much like an integer, but with only two possible values: 0 or 1, which is either false or true.

integer - a number with no decimals, e.g 3 or 42.

float (sometimes referred to as double) - a number that may include decimals, e.g. 42.3 or 10.9.

string - A number of characters, which combined makes a text string.

Besides that, there are a couple of more complex datatypes:

array - holds an array of items, e.g. several strings or several integers. An array may contain variables which are arrays which are arrays and so on.

object - a reference to an instance of a class. This is related to Object Oriented programming, which we will talk more about later on in this tutorial.

There are also a couple of special types:

resource - holds a reference to a special external resource. It may be a file resource, or perhaps an open database connection.

NULL - a value of null is nothing. It's not the same as 0 (zero), because that's actually a value. Null is truly nothing. Variables which have not yet been assigned a value, or which you have used the unset() method on, will carry the NULL value. This is useful if you wish to check whether or not a variable contains any value - you may compare it against the NULL constant.

In the next couple of chapters, we will look into working with both strings and numbers (integers and floats), and later on, we will look into both arrays and objects.


In this chapter, we will work with some numbers. As mentioned in a previous chapter, PHP have two different data types related to numbers: Integers and floats. Integers are whole numbers, without a decimal separator, while floats always carry a fractional part as well. In most cases, integers will be sufficient, and they are faster and simpler to work with.

Let's try some simple calculations, to show you how easy it is to do math with PHP. Here are a couple of examples.

<?php
$number1 = 6;
$number2 = 2;

echo "Addition: " . ($number1 + $number2);
echo "<br /><br />";
echo "Substraction: " . ($number1 - $number2);
echo "<br /><br />";
echo "Multiplication: " . ($number1 * $number2);
echo "<br /><br />";
echo "Division: " . ($number1 / $number2);
echo "<br /><br />";
?>


Now that's simple! Basic math with PHP, and it looks kinda like using a simple calculator. But what about numbers which comes from the outside world, e.g. from a submitted form? We will dig into in a later chapter, and one of the techniques we will be using, is checking if a variable holds a value that we can use for math. The is_numberic() function will help us with this. It checks whether a variable is an integer, or if it can be converted to one. For instance, "42" can be converted to 42, but "Hello World", well, that's a tough one. is_numberic will return true in the first case and false in the second case. Here is an example:

<?php
$number1 = "10";
$number2 = 20;

if((is_numeric($number1)) && (is_numeric($number2)))
    echo "Result: " . ($number1 + $number2);
else
    echo "Both variables have to be numbers!";
?>

Now, try changing "10" to a word or a sentence, e.g. "Hello world". You will see that the condition fails, and our warning will be printed. This comes in handy when validating user input, as we will see later on.

In some situations, you may need a real integer instead of a string that is numeric, like in the above example. Even though PHP is loosely typed, type casting does exist - you may cast one type to another. Have a look at this example:

<?php
$var = "30";
echo "The current datatype of var is: " . gettype($var) . "<br /><br />";
$var = (int)$var;
echo "The current datatype of var is: " . gettype($var);
?>

We use the int keyword, inside a set of parentheses, to define a new type for the variable. Obviously, it works the other way around as well - you may cast an integer to become a string and so on.
Floats
As mentioned, there are two different data types for working with numbers: Integers and floats. In the next example, I will try to show you the difference. Try running this piece of sample code:

<?php
$number1 = 10;
$number2 = 3;
$number3 = 5;

$result = $number1 / $number2;

echo "Result as a float: " . $result . "<br /><br />";
echo "Result as a float, rounded: " . round($result, 2) . "<br /><br />";
echo "Result as an integer: " . (int)$result . "<br /><br />";
echo "Multiplication as a float: " . ($result * $number3) . "<br /><br />";
echo "Multiplication as an integer: " . ((int)$result * $number3) . "<br /><br />";
?>

php functions

A function in PHP, and any other programming language, allows you to encapsulate a piece of code and call it from other parts of your code. This makes it possible to write code which can be re-used from different parts of your application, without actually writing the code over and over again. Here is an example of a simple PHP function:

<?php
function SayHello($to)
{
    echo "Hello, ".$to;
}
?>

A function should always start with the keyword function, followed by the name of the function you wish to declare. In this case, we name our function SayHello. It should be followed by a set of parentheses, which allows you to define parameters for the function. Parameters are not required, but if you don't have any, you should still write the parentheses, like SayHello(). With our function, we define the $to parameter. Since PHP is a typeless language, you don't have to define a type for the parameter, and you may send any kind of datatype through the function. The content of our function is between a set of curly braces, in this case a simple echo statement, where we use the $to parameter to send a greeting to a specific person or thing.

You use the function simply by writing the name and the required set of parameters, like this:

<?php
function SayHello($to)
{
    echo "Hello, ".$to;
}

SayHello("World");
?>

Functions may return values as well. In the first example we don't, since it's not required, but it is possible and very useful as well. If you have used other programming languages, you might be used to declaring whether or not a function should return anything, and if so, which type it will be. However, this is not needed with PHP. Let's change our function so it returns the required string instead of outputting it:

<?php
function SayHello($to)
{
    return "Hello, ".$to;
}

echo SayHello("World");
?>

As you can see, we simply have the function return the string instead of outputting it, and then we do the actual output once we call the function. This is normally how it's done, since outputting stuff directly from the string requires it to be positioned where we want the output, instead of in the top of our document or an include file.

A very important aspect of functions is the scope. Once you enter a function, you enter a new scope, and while functions and classes are automatically global, variables are not. This means that a variable declared outside a function is not automatically available inside it. Try this example to see it for your self:

<?php
$var = "test";

function SayHello()
{
    return "Current value of var: ".$var;
}

echo SayHello();
echo "<br /><br />";
echo "Current value of var: ".$var;
?>

The result will be that the first output won't have a value for $var, because it's simply not known within the function. You could declare it inside the function, and assign a value to it, but it would not be reflected outside the function. However, it is possible to get access to the outside variables within a function - you simply need to declare them as globals inside the scope of the function, like this:

<?php
$var = "test";
function SayHello()
{
    global $var;
    return "Current value of var: ".$var;
}
?>

When declaring a function, you may define one or several parameters to be optional. It's done by giving them a default value in the declaration. More than one parameter can be optional, but only the last X number of parameters can be optional - you can't have an optional parameter followed by a required parameter. In the next example, we define a couple of optional parameters to show you how it's done.

<?php
function GreetCoder($name, $msg = "Hello, coder!")
{
    echo "A message to " . $name . ": " . $msg;
}

GreetCoder("John Doe");
echo "<br /><br />";
GreetCoder("John Doe", "This is a custom message!");
?>

As you can see, we can call the function with only one parameter or with both parameters. The output is affected by what we do, but no matter what, $msg will have a value. It can come in handy in a lot of situations, which you will experience your self once you write more PHP.
Next 

php abstract class

Abstract classes are special because they can never be instantiated. Instead, you typically inherit a set of base functionality from them in a new class. For that reason, they are commonly used as the base classes in a larger class hierarchy. In the chapter on inheritance, we created an Animal class and then a Dog class to inherit from the Animal class. In your project, you may very well decide that no one should be able to instantiate the Animal class, because it's too unspecific, but instead use a specific class inheriting from it. The Animal class will then serve as a base class for our own little collection of animals.

A method can be marked as abstract as well. As soon as you mark a class function as abstract, you have to define the class as abstract as well - only abstract classes can hold abstract functions. Another consequence is that you don't have to (and can't) write any code for the function - it's a declaration only. You would do this to force anyone inheriting from your abstract class to implement this function and write the proper code for it. If you don't, PHP will throw an error. However, abstract classes can also contain non-abstract methods, which allows you to implement basic functionality in the abstract class. Let's go on with an example. Here is the abstract class:

abstract class Animal
{
    public $name;
    public $age;
   
    public function Describe()
    {
        return $this->name . ", " . $this->age . " years old";   
    }
   
    abstract public function Greet();
}

As you can see, it looks like a regular exception, but with a couple of differences. The first one is the abstract keyword, which is used to mark both the class it self and the last function as abstract. As mentioned, an abstract function can't contain any body (code), so it's simply ended with a semi-colon as you can see. Now let's create a class that can inherit our Animal class:

class Dog extends Animal
{
    public function Greet()
    {
        return "Woof!";   
    }
   
    public function Describe()
    {
        return parent::Describe() . ", and I'm a dog!";   
    }
}


As you can see, we implement the both functions from the Animal class. The Greet() function we are forced to implement, since it's marked as abstract - it simply returns a word/sound common to the type of animal we are creating. We are not forced to implement the Describe() function - it's already implemented on the Animal class, but we would like to extend the functionality of it a bit. Now, the cool part is that we can re-use the code implemented in the Animal class, and then add to it as we please. In this case, we use the parent keyword to reference the Animal class, and then we call Describe() function on it. We then add some extra text to the result, to clarify which type of animal we're dealing with. Now, let's try using this new class:

$animal = new Dog();
$animal->name = "Bob";
$animal->age = 7;
echo $animal->Describe();
echo $animal->Greet();
Next 

connecting to mysql using php

 Connecting to a MySQL database with PHP is very easy. It can be done using a single function from the nice array of MySQL related functions in PHP:

mysql_connect("localhost", "username", "password");

If default values have been configured in your configuration file, you can leave out these parameters, but otherwise you will need to specify a host and typically a username and a password for it. Both the username and password has been set by yourself or by your hosting company. If you host MySQL on your own machine, or if you run your PHP code on your hosting company's server, you can usually just specify localhost as the host value. If in doubt, ask your hosting company or check their support pages.

The mysql_connect() function returns a resource, a direct link to the database server, which should be used to access the database server each time you use one of the MySQL functions. However, if this resource is not specified, PHP will just use the last opened connection, allowing you to write less code. In most cases you will only need one MySQL connection per page, so this should work just fine for you.

To work with a database, you need to call one more function, the mysql_select_db() function. The name really tells it all - for a specific connection, it selects a database that you will be working with. It's very simple to use:

mysql_select_db("my_database");

This should be called after you have established the connection using mysql_connect(). It takes one or two parameters. The first should be the name of the database you wish to use. The second one is optional and allows you to specify which MySQL resource link the function should be performed on. Here is an example where we use these two essential functions together:


mysql_connect("localhost", "username", "password");
mysql_select_db("my_database"); 
 
And here is the same example, but where we get the resource link from mysql_connect() and use it. This is the way you should do it mainly if you need to connect to more than one database server on the same page:
 
 
$dbConnection = mysql_connect("localhost", "username", "password");
mysql_select_db("my_database", $dbConnection);


With this, we now have a connection to the database server and we have selected the desired database. In the next chapter, we will use this connection, but before we do so, we should talk a bit about closing the connection again. A connection to a database server is costly, so it should obviously be closed once we're done using it. However, PHP can and will do this for us automatically, if we choose not to do it, once the page is fully executed. If we for some reason want to close a MySQL connection before the page is done executing, we can do it by using the mysql_close() function:

mysql_close();

This will close the last opened connection. If we want to close a specific connection, just pass its link to the function:

mysql_close($dbConnection);

RSS

Categories

Followers

Blog Archive

rTechIndia

RtechIndia->technology ahead

rtech

rtechindia

RtechIndia

Go rtechindia

Go rtechindia

RtechIndia

Sunday 22 April 2012

php datatypes

PHP consists of 4 basic data types:
boolean - a boolean is actually much like an integer, but with only two possible values: 0 or 1, which is either false or true.

integer - a number with no decimals, e.g 3 or 42.

float (sometimes referred to as double) - a number that may include decimals, e.g. 42.3 or 10.9.

string - A number of characters, which combined makes a text string.

Besides that, there are a couple of more complex datatypes:

array - holds an array of items, e.g. several strings or several integers. An array may contain variables which are arrays which are arrays and so on.

object - a reference to an instance of a class. This is related to Object Oriented programming, which we will talk more about later on in this tutorial.

There are also a couple of special types:

resource - holds a reference to a special external resource. It may be a file resource, or perhaps an open database connection.

NULL - a value of null is nothing. It's not the same as 0 (zero), because that's actually a value. Null is truly nothing. Variables which have not yet been assigned a value, or which you have used the unset() method on, will carry the NULL value. This is useful if you wish to check whether or not a variable contains any value - you may compare it against the NULL constant.

In the next couple of chapters, we will look into working with both strings and numbers (integers and floats), and later on, we will look into both arrays and objects.


In this chapter, we will work with some numbers. As mentioned in a previous chapter, PHP have two different data types related to numbers: Integers and floats. Integers are whole numbers, without a decimal separator, while floats always carry a fractional part as well. In most cases, integers will be sufficient, and they are faster and simpler to work with.

Let's try some simple calculations, to show you how easy it is to do math with PHP. Here are a couple of examples.

<?php
$number1 = 6;
$number2 = 2;

echo "Addition: " . ($number1 + $number2);
echo "<br /><br />";
echo "Substraction: " . ($number1 - $number2);
echo "<br /><br />";
echo "Multiplication: " . ($number1 * $number2);
echo "<br /><br />";
echo "Division: " . ($number1 / $number2);
echo "<br /><br />";
?>


Now that's simple! Basic math with PHP, and it looks kinda like using a simple calculator. But what about numbers which comes from the outside world, e.g. from a submitted form? We will dig into in a later chapter, and one of the techniques we will be using, is checking if a variable holds a value that we can use for math. The is_numberic() function will help us with this. It checks whether a variable is an integer, or if it can be converted to one. For instance, "42" can be converted to 42, but "Hello World", well, that's a tough one. is_numberic will return true in the first case and false in the second case. Here is an example:

<?php
$number1 = "10";
$number2 = 20;

if((is_numeric($number1)) && (is_numeric($number2)))
    echo "Result: " . ($number1 + $number2);
else
    echo "Both variables have to be numbers!";
?>

Now, try changing "10" to a word or a sentence, e.g. "Hello world". You will see that the condition fails, and our warning will be printed. This comes in handy when validating user input, as we will see later on.

In some situations, you may need a real integer instead of a string that is numeric, like in the above example. Even though PHP is loosely typed, type casting does exist - you may cast one type to another. Have a look at this example:

<?php
$var = "30";
echo "The current datatype of var is: " . gettype($var) . "<br /><br />";
$var = (int)$var;
echo "The current datatype of var is: " . gettype($var);
?>

We use the int keyword, inside a set of parentheses, to define a new type for the variable. Obviously, it works the other way around as well - you may cast an integer to become a string and so on.
Floats
As mentioned, there are two different data types for working with numbers: Integers and floats. In the next example, I will try to show you the difference. Try running this piece of sample code:

<?php
$number1 = 10;
$number2 = 3;
$number3 = 5;

$result = $number1 / $number2;

echo "Result as a float: " . $result . "<br /><br />";
echo "Result as a float, rounded: " . round($result, 2) . "<br /><br />";
echo "Result as an integer: " . (int)$result . "<br /><br />";
echo "Multiplication as a float: " . ($result * $number3) . "<br /><br />";
echo "Multiplication as an integer: " . ((int)$result * $number3) . "<br /><br />";
?>

php functions

A function in PHP, and any other programming language, allows you to encapsulate a piece of code and call it from other parts of your code. This makes it possible to write code which can be re-used from different parts of your application, without actually writing the code over and over again. Here is an example of a simple PHP function:

<?php
function SayHello($to)
{
    echo "Hello, ".$to;
}
?>

A function should always start with the keyword function, followed by the name of the function you wish to declare. In this case, we name our function SayHello. It should be followed by a set of parentheses, which allows you to define parameters for the function. Parameters are not required, but if you don't have any, you should still write the parentheses, like SayHello(). With our function, we define the $to parameter. Since PHP is a typeless language, you don't have to define a type for the parameter, and you may send any kind of datatype through the function. The content of our function is between a set of curly braces, in this case a simple echo statement, where we use the $to parameter to send a greeting to a specific person or thing.

You use the function simply by writing the name and the required set of parameters, like this:

<?php
function SayHello($to)
{
    echo "Hello, ".$to;
}

SayHello("World");
?>

Functions may return values as well. In the first example we don't, since it's not required, but it is possible and very useful as well. If you have used other programming languages, you might be used to declaring whether or not a function should return anything, and if so, which type it will be. However, this is not needed with PHP. Let's change our function so it returns the required string instead of outputting it:

<?php
function SayHello($to)
{
    return "Hello, ".$to;
}

echo SayHello("World");
?>

As you can see, we simply have the function return the string instead of outputting it, and then we do the actual output once we call the function. This is normally how it's done, since outputting stuff directly from the string requires it to be positioned where we want the output, instead of in the top of our document or an include file.

A very important aspect of functions is the scope. Once you enter a function, you enter a new scope, and while functions and classes are automatically global, variables are not. This means that a variable declared outside a function is not automatically available inside it. Try this example to see it for your self:

<?php
$var = "test";

function SayHello()
{
    return "Current value of var: ".$var;
}

echo SayHello();
echo "<br /><br />";
echo "Current value of var: ".$var;
?>

The result will be that the first output won't have a value for $var, because it's simply not known within the function. You could declare it inside the function, and assign a value to it, but it would not be reflected outside the function. However, it is possible to get access to the outside variables within a function - you simply need to declare them as globals inside the scope of the function, like this:

<?php
$var = "test";
function SayHello()
{
    global $var;
    return "Current value of var: ".$var;
}
?>

When declaring a function, you may define one or several parameters to be optional. It's done by giving them a default value in the declaration. More than one parameter can be optional, but only the last X number of parameters can be optional - you can't have an optional parameter followed by a required parameter. In the next example, we define a couple of optional parameters to show you how it's done.

<?php
function GreetCoder($name, $msg = "Hello, coder!")
{
    echo "A message to " . $name . ": " . $msg;
}

GreetCoder("John Doe");
echo "<br /><br />";
GreetCoder("John Doe", "This is a custom message!");
?>

As you can see, we can call the function with only one parameter or with both parameters. The output is affected by what we do, but no matter what, $msg will have a value. It can come in handy in a lot of situations, which you will experience your self once you write more PHP.
Next 

php abstract class

Abstract classes are special because they can never be instantiated. Instead, you typically inherit a set of base functionality from them in a new class. For that reason, they are commonly used as the base classes in a larger class hierarchy. In the chapter on inheritance, we created an Animal class and then a Dog class to inherit from the Animal class. In your project, you may very well decide that no one should be able to instantiate the Animal class, because it's too unspecific, but instead use a specific class inheriting from it. The Animal class will then serve as a base class for our own little collection of animals.

A method can be marked as abstract as well. As soon as you mark a class function as abstract, you have to define the class as abstract as well - only abstract classes can hold abstract functions. Another consequence is that you don't have to (and can't) write any code for the function - it's a declaration only. You would do this to force anyone inheriting from your abstract class to implement this function and write the proper code for it. If you don't, PHP will throw an error. However, abstract classes can also contain non-abstract methods, which allows you to implement basic functionality in the abstract class. Let's go on with an example. Here is the abstract class:

abstract class Animal
{
    public $name;
    public $age;
   
    public function Describe()
    {
        return $this->name . ", " . $this->age . " years old";   
    }
   
    abstract public function Greet();
}

As you can see, it looks like a regular exception, but with a couple of differences. The first one is the abstract keyword, which is used to mark both the class it self and the last function as abstract. As mentioned, an abstract function can't contain any body (code), so it's simply ended with a semi-colon as you can see. Now let's create a class that can inherit our Animal class:

class Dog extends Animal
{
    public function Greet()
    {
        return "Woof!";   
    }
   
    public function Describe()
    {
        return parent::Describe() . ", and I'm a dog!";   
    }
}


As you can see, we implement the both functions from the Animal class. The Greet() function we are forced to implement, since it's marked as abstract - it simply returns a word/sound common to the type of animal we are creating. We are not forced to implement the Describe() function - it's already implemented on the Animal class, but we would like to extend the functionality of it a bit. Now, the cool part is that we can re-use the code implemented in the Animal class, and then add to it as we please. In this case, we use the parent keyword to reference the Animal class, and then we call Describe() function on it. We then add some extra text to the result, to clarify which type of animal we're dealing with. Now, let's try using this new class:

$animal = new Dog();
$animal->name = "Bob";
$animal->age = 7;
echo $animal->Describe();
echo $animal->Greet();
Next 

connecting to mysql using php

 Connecting to a MySQL database with PHP is very easy. It can be done using a single function from the nice array of MySQL related functions in PHP:

mysql_connect("localhost", "username", "password");

If default values have been configured in your configuration file, you can leave out these parameters, but otherwise you will need to specify a host and typically a username and a password for it. Both the username and password has been set by yourself or by your hosting company. If you host MySQL on your own machine, or if you run your PHP code on your hosting company's server, you can usually just specify localhost as the host value. If in doubt, ask your hosting company or check their support pages.

The mysql_connect() function returns a resource, a direct link to the database server, which should be used to access the database server each time you use one of the MySQL functions. However, if this resource is not specified, PHP will just use the last opened connection, allowing you to write less code. In most cases you will only need one MySQL connection per page, so this should work just fine for you.

To work with a database, you need to call one more function, the mysql_select_db() function. The name really tells it all - for a specific connection, it selects a database that you will be working with. It's very simple to use:

mysql_select_db("my_database");

This should be called after you have established the connection using mysql_connect(). It takes one or two parameters. The first should be the name of the database you wish to use. The second one is optional and allows you to specify which MySQL resource link the function should be performed on. Here is an example where we use these two essential functions together:


mysql_connect("localhost", "username", "password");
mysql_select_db("my_database"); 
 
And here is the same example, but where we get the resource link from mysql_connect() and use it. This is the way you should do it mainly if you need to connect to more than one database server on the same page:
 
 
$dbConnection = mysql_connect("localhost", "username", "password");
mysql_select_db("my_database", $dbConnection);


With this, we now have a connection to the database server and we have selected the desired database. In the next chapter, we will use this connection, but before we do so, we should talk a bit about closing the connection again. A connection to a database server is costly, so it should obviously be closed once we're done using it. However, PHP can and will do this for us automatically, if we choose not to do it, once the page is fully executed. If we for some reason want to close a MySQL connection before the page is done executing, we can do it by using the mysql_close() function:

mysql_close();

This will close the last opened connection. If we want to close a specific connection, just pass its link to the function:

mysql_close($dbConnection);