Try and Catch (…me if you can)

PHP is a great language for creating dynamic websites and has a lot of functions to do just about everything on the server side.

Only, with all those functions you need a good error handler. The other languages like perl, c, c# etc. have a try and catch function. As of version 5, this function is also available in PHP. In this post I will try to explain to usage and benefits of try and catch. Ready ?

Example:
Let's say you have a website with some blog posts. Visitors can view the latest post by going to www.example.com/?posts
You also create a page to let visitors read a single post. They'll go to: www.example.com/?posts&item=1
This will tell your script that it needs to get item #1 from the database and display it. Now, as we all know, visitors will try all sorts of things, for example: www.example.com/?posts&item=blablabla. This well tell your script that it should fetch item #blablabla from the database which, ofcourse, does not exist and you get a pretty MySQL error.

Try and Catch
Try and catch works by 'throwing errors'. The script executes a try block and if an error is thrown, the try block will end and the catch function will be executed.

try {
    if (isset($_GET['item'])) {
        $postId = mysql_real_escape_string($_GET['item']);
        $qryPost = "SELECT * FROM posts WHERE id = $postId";

    if (!$rsltPost = mysql_query($qryPost)) {
        Throw new Exception();
    }
    if (!mysql_num_rows($rsltPost)) {
        Throw new Exception();
    }
    $arrPost = mysql_fetch_array($rsltPost);
    echo $arrPost[1];
    }
}
catch (Exception $e) {
    echo "There is no such post!";
}

Try
For starters, all the code that we want to error check, needs to be in the try statement. So we start with:

try {

Next is the code to check whether the URL contains the item variable and if it does, execute the code to display that item. Ofcourse we sanitize the variable before sending it to the database.

if (isset($_GET['item'])) {
    $postId = mysql_real_escape_string($_GET['item']);

Query
Normally I write my queries like this:

$qryPost = mysql_query ("SELECT * FROM Posts WHERE id = $postId") or die (mysql_error());

That works fine for most queries. The downside is that when an error occurs, the script dies and displays an error message which could reveal some of your MySQL configuration to the visitor!
We are going to write our query like this:

$qryPost = "SELECT * FROM posts WHERE id = $postId";

Next we're going to evaluate the query and check if it runs without an error:

if (!$rsltPost = mysql_query($qryPost)) {
        Throw new Exception();
    }

As you see, if the query fails, an error is thrown. this will stop the rest of the try statement from executing and go to the catch statement. The same goes for the second if statement. Only this time it checks if the query returns a row.

Catch
The catch statement is executed when an error is thrown.

catch (Exception $e) {
    echo "There is no such post!";
}

Will only echo "There is no such post!" and the rest of your script/site will continue to function.
The try statement also has some debugging features. You can, for example, get the script line on which the error is thrown, or the exact error message.

This is just a basic example of how to use try and catch. You can read more in the php manual

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


Are we killing the internet?

Over the past couple of years I have been “into” developing unique and interesting websites.
Developing websites in general is not an easy task. Sure, you can download some awful program to quickly produce a web page, but designing and coding an entire site that is both visually pleasing and user friendly is not so easy, contrary to popular belief. But that’s for another blog post ;) .

Anyway, when developing a large scale website one of the most important things you have to consider is “how do I make money with this?”. In the past you basically needed two things, adverts and traffic. Once you had those two things sorted out you were good to cash in cheques.

These days however, people have advert blockers, to which I am hugely against. I have never had an advert blocker installed on my PC, and never will. One of the main reasons for this is because I understand from a web developers point of view how difficult it is to make money online. A lot of people consider the internet “the place to be” to make money, as if its easy, but its not. Web developers spend weeks and months perfecting their websites to make it earn money. Which is why I find someone surfing my websites with an ad blocker installed repulsive.

Advertisements power the internet and they give the people that produce the websites we all love, the incentive to carry on producing new and interesting content.
I can fully understand it when you surf to a website and instantly 10,000 popup’s flood the screen. But should you really rush off and download a advert blocker because of that one site? I don’t think so.
I’d just navigate away from that website or find a piece of software to block the adverts on that particular site.

You probably think I am being a bit of a hypocrite for saying that, but I’m not.
Adverts on sites should blend into the user experience, not drive them crazy. If they do they deserve to be blocked - but just on that site!

Websites usually have very few revenue streams, adverts are one of the most important of those.

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


My New SIte - FetchMP3.COM - Search . Convert . Download

Hello!

Its been a while since my last blog post but I’m at least making it a good one!

I have spent a couple of months developing my latest project which is http://www.fetchmp3.com. It is a unique site that allows you to search for videos on popular video sites, and download the MP3 version of a particular video.

This site is one of a kind. You don’t need to navigate to a million pages, or download some spyware infested programme. The website will do it all seamlessly - you’ll love it!

Have a look at this video of the site in use, it is unbelievably simple.

Watch out for new features, as there are plenty in the works, believe me!

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


PAPAFACE.COM is hiring!

Hello,

Well as you may have noticed the updates around here are very few and far between. That’s why I have come to the decision of employing a blogger to publish interesting and unique posts on here just like MINE :D

If you want to apply just email me at papa.face @ gmail.com (no spaces). Past experience would be beneficial and please state how much you would expect. No time wasters please.

I am looking to hire someone with immediate effect.

Come-hither!

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


Youtube Without The Video

Hello there,
It has been a while since I posted something new on my blog, I’ve just been to busy lately.

Today I am going to show you how to put a Youtube video on your website but in a way that only allows you to hear the video rather than being able to see it as well.

Why would I want to do that?
I hear you say. Well sometimes you might want to put music on a page. Youtube is an ideal place to get music from.
Of course you can simply put the video in the page as you would normally do, but that big intrusive box can be annoying at times, especially on myspace etc.

Although this may not be much use to you, it is a nice trick to know :)

You can use this tool to produce the code needed!

The tool allows you to put in Play and Stop controls, but they only work for Firefox.

Feel free to show me a better way to do this if there is one :)

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


MySQL - Connecting, Selecting…. and more.

Today I am going to show you various things that you can do with MySQL using PHP.
I am going to assume you have fairly good knowledge of PHP while following these instructions.

Connecting to MySQL

Connecting to MySQL is extremely simple. I am going to presume you know your MySQL credentials, if you don't know them, find them out ;) .

$databasehost = "localhost"; //put your MySQL host into this variable. It is usually localhost
$databaseusername = "root"; //put your MySQL username into this variable.
$databasepassword = "somethingreallydifficulttoguess"; //put your MySQL password into this variable.
// I have used long variable names because the likelihood of them being overwritten is unlikely.
$conn = mysql_connect($databasehost,$databaseusername,$databasepassword) or die (mysql_error());
 

And thats it. In the event that your credentials are incorrect and error will be produced.

Creating a MySQL database using PHP

Creating a database in PHP is extremely simple.

mysql_query("CREATE DATABASE `database_name`",$conn) or die (mysql_error());
//this will create a database called "database_name" and use the connection we established earlier to create that database.
 

Selecting the MySQL database

Selecting the MySQL database is even simpler. Once you know your database name you can use this code to select the database:

$databasename = "database_name"; // the name of the database you want to select.
mysql_select_db($databasename,$conn) or die (mysql_error());
//the database you created earlier is now selected. If you already have a database created, you do not need to run the CREATE DATABASE code obviously.
 

Creating a MySQL table within a database

Things start to get a bit more complicated when it comes to creating tables. You may want to look at the MySQL website to get some more information on how to create tables using SQL.

Here is how we would create a table called "new_table" in the database.

mysql_query("CREATE TABLE `new_table` (`id` int NOT NULL AUTO_INCREMENT,`name` varchar(25),`age` int, PRIMARY KEY(id))",$conn) or die(mysql_error());
 

This code will create a table with 3 fields in (id - which is the primary key, name which allows up to 25 alphanumeric characters and age that allows an integer) .

Retrieving data from a MySQL table

I am going to show you a basic way of getting data from a table when you know all the field names of that database.
There are numerous ways of doing this (look into mysql_fetch_assoc() and mysql_fetch_array())

$select = mysql_query("SELECT `id`,`name`,`age` FROM `new_table`") or die (mysql_error());
if (mysql_num_rows($select) > 0)
 {
 while (list($_id,$_name,$_age) = mysql_fetch_array($select)) //gets the data from the SELECT query and puts it into variables
  {
   echo "The ID for this record is: " . $_id . "\n";
   echo "The Name for this record is: " . $_name . "\n";
   echo "The Age for this record is: " . $_age . "\n";
  }
 }
else
 {
 echo "There are no records to display";
 }
 

The above example is the way I sometimes chose to do my SELECT queries because it is quite self explanatory with the variables. I would not recommend this method however if you have a lot of variables in your script as it could pose problems with overwriting variables.

This is another way of performing the same query:

$select = mysql_query("SELECT * FROM `new_table`") or die (mysql_error());
if (mysql_num_rows($select) > 0)
 {
 while ($row = mysql_fetch_assoc($select)) //gets the data from the SELECT query and puts it into the $row array
  {
   echo "The ID for this record is: " . $row['id'] . "\n";
   echo "The Name for this record is: " .  $row['name'] . "\n";
   echo "The Age for this record is: " .  $row['age'] . "\n";
  }
 }
else
 {
 echo "There are no records to display";
 }
 

The above does the same thing as the example beforehand, but utilizes only one variable.

Deleting data from a MySQL table
The DELETE query is extremely simple. You simply define the table from which you'd like to delete a record, and specify a record. In this case we are specifying the record with an id of 1.

$del = mysql_query("DELETE FROM `new_table` WHERE `id`= '1' ",$conn) or die(mysql_error());
if (mysql_affected_rows() == 1)
 {
 echo "Record Deleted";
 }
else
 {
 echo "There was a problem deleting the specified record.";
 }
 

Dropping a table from a MySQL database
If you would like to remove a table and all its data from a MySQL database then use the following code:

$drop = mysql_query("DROP TABLE `new_table` ",$conn) or die(mysql_error());
  if($drop)
   {
    echo "new_table has been dropped from the database.";
   }
 

Inserting data into a table
Inserting data into a table is extremely simple.

$insert = mysql_query("INSERT INTO `tblname` (`name`,`username`,`email`) VALUES ('Andrew','papa_face','someone@somewhere.com')",$conn) or die(mysql_error());
  if($insert)
   {
    echo "The record has been inserted into the database.";
   }
 

Of course you can make insert queries dynamic by using variables, but that is one quick and easy example of how to insert data into a table :) .

And that's it!
I hope this blog post have been very informative. Any questions or comments are greatly appreciated.
Thanks for reading!

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


Sanitizing $_POST and $_GET

Hey,
Well I haven't posted something PHP related for quite a few days now so I thought I'd show you something I use in every single script that I write that involves form submissions or URL data.
It is important to escape (sanitize) all data from forms that may be used in a mysql database query.
If you use some other database type, the function can easily be modified.

Place this code at the top of all your pages (maybe via an include):

        if(!function_exists(mysql_real_escape_array))
                {
        function mysql_real_escape_array($t)
                        {
        return array_map("mysql_real_escape_string",$t);
                        }
                }

        mysql_real_escape_array($_GET);
        mysql_real_escape_array($_POST);
 

It will automatically sanitize all your $_POST (from forms) and $_GET (URL data) to help prevent SQL injections.

Be aware though, that this is just one precaution you should take when inserting data into a mysql database.

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


FORTRAN and Other Programming Languages from the 50’s

FORTRAN-FORmula TRANslating system was invented in the year 1957. The language was very easy to use as it contained limited commands like GOTO, IF and DO. FORTRAN paved the way for today’s languages as it contained basic data types like integer, double precision, logical variables and real numbers which are very much used in today’s languages.

As in those days people were only looking for solving mathematical operations via programming languages, FORTRAN was a result of that need. This is why FORTRAN was amazing with numbers but was not the same in other areas, like handling input and output. As a result the language was not famous amongst businesses. When computers started getting into the businesses in the year 1959 A.D. the need for another language arose.

This is why COBOL was invented. From the beginning itself, COBOL was developed as a businessman’s language. The language was easier than FORTRAN to understand as it had only two types of data types; strings and numbers. The main feature of COBOL was to handle records, as businesses needed to keep an account of previous records. COBOL statements were related to the English language. This made it very easy for the businessman to get the grasp of the language better and they were able to adapt it easily.

In the year 1958 A.D. a new type of language was designed. It was called LISP-LISt Processing language. The main reason for the invention of this language was to explore the field of artificial intelligence. Syntax of the language was different from all the existing languages as the language dealt with a completely new area of concern. As the name suggests, the program in the LISP language are written as a set of lists that represents series of items. As a result of this the LISP programs have a distinctive ability to modify itself from time to time and consequently to develop on its own.

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


Programming on Electronic Devices

Computers cannot interpret human languages. They have their own language which is known as binary language. It is the language of 0’s and 1’s. So to command or program a computer to get the desired results one had to first convert the program from human language to the binary language. This was done by converting each line of the program into binary language and feed it into the memory line by line. This was how the computers in those days were programmed.

Shortly after the invention of John Von Neumann’s models, the first ever programming language to be programmed on an electronic device named Short Code was devised in the year 1949 A.D. In this language human help was needed to convert the program into binary language and feed it into the memory. This job of converting the program line by line into binary language was proving to be a tedious and time consuming work.

This is when the compiler was invented. The first compiler was named A-0 by its inventor, Mr. Grace Hopper in the year 1951 A.D. A compiler is a program which automatically converts the human language into the machine understandable language that is the binary language. The invention of the compiler made programming simple and very efficient. Now a lot of time was saved as the machine could itself translate human language into the machine readable language and the programmer was saved from the tedious job of interpreting.

In the year 1957 A.D. the first major programming language which appeared due to the inventions and work of earlier scientists was FORTRAN-FORmula TRANslating. This programming language was invented by International Business Machines (IBM). They invented FORTRAN for computing science related queries. The language was a breakthrough in programming. It was a big step towards the start of making high end languages. Today FORTRAN is nothing compared to modern languages because it contained limited commands such as DO, GOTO and IF statements, but these commands were innovative in those days.

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


How It All Began…

The traces of programming can be found as early as 2000 years ago with the invention of Abacus, a device made of wood which had two parallel strings fixed horizontally on it. On these strings, beads were embedded. Using programming rules which were decided by the scholars of those days, addition and subtraction of numbers was made possible using Abacus. Another significant programming development which was invented around the same time is the Astroble. This device proved to be very useful for navigation in those days.

These instruments, Abacus and Astroble were used significantly for many centuries until the discovery of the digital computer or in simple terms, a calculator by which it is known popularly was made. The famous mathematician Blaise Pascal is known for programming the first calculator in 1642. The device build by Pascal used to take numbers as inputs and used to give their addition as output. Pascal programmed the device in such a way that the numbers had to be entered via dials. Pascal invented this device in order to help his father save time in his calculations as he was a tax collector.

In the year 1671 A.D., a scientist named Gottfried Wilhelm Von Leibniz designed a computer. He claimed that his designed computer would be able to perform mathematical operations such as addition and subtraction and after making some modifications he was convinced that it could also perform multiplication. Due to financial crisis he was not able to convert his designed model into a reality. But he didn’t lose hope and in the year 1694 he was finally able to prove his design. He successfully programmed a computer that could perform the mathematical operations which he had claimed 23 years ago.

The programming techniques invented by Leibniz and Pascal were not accepted by their colleagues. Their inventions were considered weird for almost a century. But they were soon accepted by the new age scientists for making faster programming techniques and till today we use the same technique which they invented centuries ago.

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


John Von Neumann’s Two Programming Models

In 1945 a revolutionizing concept was invented which would change the way programming was performed. A scientist named John Von Neumann working at the prestigious Institute for Advanced studies in Princeton, New Jersey created two programming models. John named the models as “Shared Program Technique” and “Conditional Control Transfers”.

John was very concerned about the fact that the ENIAC was a success even though it used a lot of technology that was similar to the previous technologies. The ENIAC was a computer that had a complicated structure and was of undefined physical dimensions. Sometimes the computers were so large that they would occupy an entire floor. John suggested that a computer should have a simple structure and its size should be smaller than usual.

This is what John has tried explaining in the “Shared Program Technique” model. He created awareness among people that a computer need not be as large as they used to be at that time. He also told them that a computer can be a lot faster if they are programmed in a complicated structure instead of the simple mechanism that was used to design them those days. These ideas gave way to the high speed computers of today’s generation.

The main idea behind this kind of programming was to keep the computer busy all the time. As the computers of those days used to perform a single operation at a time and then used to enter wait state till the next instruction is received. So with the help of “Shared Program Technique” subroutines were created which helped in programming the computer so that it will be in busy state most of the time for the optimum utilization of the processor.

In the second model viz, “Conditional Control Transfer”, John informs us that instead of performing the program in a specific sequence i.e. line after line, there should be use of jump statement. He also suggests the use of conditional programming which is popularly known by IF-ELSE loop in today’s world. With the help of these two models the computers became much more efficient and

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


The First Programming Language

The first ever machine which calculated the difference between numbers was developed by Charles Babbage.  This machine evolved with time and is called a computer nowadays. The machine which Charles Babbage invented used to perform only one operation i.e. calculating difference between numbers. This instruction which tells the machine that it has to calculate difference between two numbers is called programming.

Earlier programming languages were a lot different than today’s. In those days the programming languages were to be embedded line by line into the processor and then execute. They were able to execute only one program at a time as the memory available was minimal. Programming languages of the previous five decades have arrived in two phases; namely primary major language and secondary major language. The latter one is what we use nowadays.

The machine that was developed by Charles Babbage used gears for executing the calculation i.e. Charles’ difference engine was only useful if the gears were changed physically. The computers of yesteryears used physical motion for the execution of programs. This method changed in 1942 with the invention of ENIAC. ENIAC was developed by the US government who were successful in replacing the physical motion by electrical signals. In the new machine’s working many of the principles were same as Babbage’s. The only way the mechanism could be programmed was by resetting the controls and rewiring the complete structure, which was very tedious.

In 1945, the Institute of Advanced Study developed two significant models in the field which straightforwardly changed the way coding languages worked in those days. The project was headed by John Von Neumann who was working at the institute. The first model was named “The Shared Program Technique” by the Institute. John named the second model as “Conditional Control Transfers”. These two models were about to change the entire system of programming in those days and give way to new age programming concepts.

 

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


The Basic: C Programming will always be popular

C is a general purpose computer coding language which works closely with hardware. C was invented by Dennis Ritchie and Ken Thompson with the help of their team mates at AT&T Bell Lab’s USA in the year 1969 but major development was made in the language in the year 1973 when it was actually published under the title “The C Programming Language”, the same year.

One would wonder why Dennis and Ken named the language as C. The reason is that in the process of developing the language they had taken a lot of features from the existing language which was called B. So the language which they created was an advanced version of the B language, which is why they named their language C, funnily.

C is a basic language which is the building block of mostly all the languages present today. The language is platform independent. That means C does not need any specific platform for running. It can work on any operating system. There are many compilers which run C. As the language works close to the hardware it uses minimal space. Also the language is easy to understand as it has a user friendly language.

If one wants to become a programmer, this is the first language he should learn. Also nowadays in academics, this language is made compulsory in computer studies. All the new languages like Java, Microsoft .Net and many other languages have used C language as their building mechanism. All these languages are easy to learn if one has knowledge of the C language.

The boundary of C language is vast. It s not limited to just programming of applications. In fact it is also used in graphical applications. There are many games which uses high end graphics built using the language. The C language is so old compared to modern languages but despite that it still it stands apart from all these powerful languages.

 

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


The Beginning of PHP

PHP - Hypertext preprocessor is basically a computer coding language. The language was designed by Rasmus Lerdorf and was developed by the PHP group. PHP was created in 1994 by Rasmus Lerdorf to help maintain his personal homepage.

He had written a bunch of Common Gateway Interface (CGI) binaries via the C coding language and wanted to restore a trivial set of Perl scripts which he had been using to preserve his homepage by the CGI. He wanted to do this in order to check the traffic on his homepage. This later was released publicly as the first ever version of Hypertext Preprocessor on 8 June, 1995 named PHP/FI (Form Interpreter).

One would wonder why there is an extra letter P in the abbreviation. The reason being the language is initialized again and again, recursively and that’s why the abbreviation PHP. PHP is an essential, object-oriented language. PHP is extensively used as an all-purpose scripting language, which is particularly fitting for web development. The working of PHP is simple. PHP essentially uses a web server to run, which takes the PHP code as input and results in web pages as output.

PHP was originally created for designing dynamic web pages. Over the years the main focus of PHP has changed. Server side scripting is the spotlight of PHP now. Moreover PHP has been declared as free software by the free software association. It is available over the internet and any one can download it. Due to this reason PHP stands out in comparison with competitors like Microsoft’s ASP.NET system, mod_perl framework and Sun Microsystems’ JavaServer Pages as they are not free. The PHP parser can run with both, a web browser and a web server which help in providing dynamic content.
The following is a simple Hello World code example for PHP:

<?php
Echo ’Hello World!’;
?>
 


[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


PHP - The Basics - Tags, echo and if/else

One of the most basic things when writing code in PHP is to use the PHP tags which signify the beginning and the ending of the PHP code. You must have the tags in order for PHP to process the code you write. The tags are:

beginning tag:

<?php

ending tag:

?>

e.g

<?php
//code here
?>
 

You can have anything proceeding/preceding the PHP tags, but anything in between them must be valid PHP.

I advise you to only use the tags that I have stated above. Try not to use tags like:

<?
//some code
?>

or

<?= "Hello!" ?>
 

Shorthand tags are not 100% compatible on 100% of servers, however:

<?php
//some code
?>

is! ;)

We’ll start with something pretty simple and it is the echo statement.
This is an example of the echo statement:

<?php
echo "Hello you!";
?>
 

When the script is run, the page will display “Hello you!”.
Notice the semicolon? The semicolon (;) is a line terminator. It tells PHP that you are finished with that particular set of instructions, and that PHP can continue with the script until it reaches the end. If the semicolon is not present at the end of instructions/commands/statements/variables a error may be triggered as a result.

Now lets move on to something a little more useful, the if/else statement.

This is an example of an if/else statement:

<?php
if (5 > 10)
 {
 echo "5 is greater than 10";
 }
else
 {
 echo "5 is not greater than 10";
 }
?>
 

Okay with an if statement you must define the conditions of the if between the brackets. The aim of an if statement, is to get true returned (a boolean). If the condition returns false, then it will run the code in the else statement (if there is one).

In the code above the if statement will return false and display “5 is not greater than 10″ - understand?

Yeah its pretty easy at this level.
If I used this code:

<?php
if (5 < 10)
 {
 echo "5 is less than 10";
 }
else
 {
 echo "5 is NOT less than 10";
 }
?>
 

The if statement would return true, and therefore we would get “5 is less than 10″ printed out on the page.

When writing an if statement there are two important parts.

  1. The condition - this is contained in between brackets (5 < 10)
  2. The curly braces - { } - the code you want to execute should be placed in between the two curly braces. The only exception to this is when you only have one line of instructions like this:
<?php
if (5 < 10)
echo "5 is less than 10";
?>
 

That concludes this part of my help guide I hope it was useful to those starting to learn PHP.
If you want to look into the if/else statement more, look into elseif. The PHP manual is a great resource, so make good use of it. It contains everything you need to know about PHP (literally).

Feel free to comment on this post, I appreciate all the comments I receive! :D

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


Data Types in PHP

PHP is not a very strict language when it comes down to data types.
Strings:

$string = "This is a string";
 

Strings are values that contain characters. This can include basically everything you can type on your keyboard.

Integers:

$string = 1;
 

Integers are values that just contain numbers. Notice in the example above that there are no quotes?
Well, you can write an integer like that, or like this:

$string = "1";
 

PHP automatically converts numbers contained in a string with no other characters into a integer. The only time you need to be careful of this is when you are using operators (I will discuss that in another post).

Boolean:

$string = true;
$string2 = false;
 

Booleans are values that contain either true or false. They can be used in if statements like:

$string = true;
if ($string)//checks if $string is true
 {
 echo '$string is true';
 }
else
 {
 echo '$string is false';
 }
 

Hope that helps you understand data types in PHP better. Obviously I have just scratched the surface in my explanations.
Feel free to comment and ask any questions :D

[Slashdot][Digg][Reddit][del.icio.us][Facebook][Technorati][Google][StumbleUpon]


How to make a Dynamic Image

Dynamic images (as I call them) are images that change depending on a condition.
A regular image URL is something like:
#1

<img src="http://www.papaface.com/blog/wp-content/themes/papaface/images/beer.png" />
 

However a Dynamic Image's URL could be something like:
#2

<img src="http://www.papaface.com/blog/somephpfile.php" />
 

Notice the difference?
Example 1's URL is actually an image file, however example 2's URL is actually a PHP file producing a dynamic image in this case.

These dynamic images are useful if you want to change the image produced at any point.

Lets say we are providing a link checking service and I want to offer the visitors the ability to put an image on their site once they've used the link checking service. The image will change to green when the link is valid, and red when it is not.

<img src="http://www.papaface.com/blog/resources/dynamicimage/example.php?id=22451" />
 

Now every time the image is loaded the script can actually look for link id "22451" in a database. It can then check the image for validity and produce a green or red image like so:

This is the code that would allow you to do this:

<?php  
       
        $linkid = $_GET['id']; //this is the link id that the script needs to look for in the database
       
        //you would open a mysql connection here
       
        $get = @mysql_query("SELECT `link` FROM `tbllinks` WHERE `linkid`='".mysql_real_escape_string($linkid)."'"); //@ suppresses the error message (this is usually a bad coding practice, but in this case we do not want anything other than an image displayed to the user.

        list($url) = mysql_fetch_array($get);
        /*The code below checks the link. If it is a valid and working link it will return a 200 code.*/
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        $info = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if      ($info == "200")
                $colour = "green";   //link is valid
        else
                $colour = "red"; //link is NOT valid