maxresdefault

PHP to MySql Database connection in WAMP Server

WAMP is an acronym formed from the initials of the operating system Microsoft Windows and the principal components of the package: Apache, MySQL and one of PHP, Perl or Python. Apache is a web server. MySQL is an open-source database. PHP, Perl and Python are scripting languages that can manipulate information held in a database and generate web pages dynamically each time content is requested by a browser. Other programs may also be included in a package, such as phpMyAdmin which provides a graphical user interface for the MySQL database manager.

Setpwise  Procedure to Create webpage ,Connect to database  and Inserting data.

1-Install Wamp Server On PC. You can Get Installation tutorial on any website.




2- Now Start the Wamp Server and  do right click and click on phpmyadmin .

PhphMyadmin page will open and clikc on New database and create new database with uyour name

Now Create new table name as info with two field name as first and last

remaing  field let it be empty.




We are done with database .Now Create Web page

3– Make Simple webpage with two textbox… First Name and Last Name

code of html page-

<html>
<head>
</head>
<body>
<h1>My First Php Web Page</h1>

<form action=”insert.php” method=”post”>
First Name: <input type=”text” name=”first”><br>
Last Name: <input type=”text” name=”last”><br>
<input type=”Submit”>
</form>
</body>
</html>
Save this file as index.html

Step 2-  Make Php File Which Handle that request-

<?php
$database=”jayesh”; //database name
$first=$_POST[‘first’];//this values comes from html file after submitting
$last=$_POST[‘last’];
$con = mysql_connect(“localhost”,”root” ,””);//for wamp 3rd feild is balnk
if (!$con)
{
die(‘Could not connect: ‘ . mysql_error());
}
mysql_select_db(“$database”, $con);

$query = “INSERT INTO info (first,last)VALUES (‘$first’,’$last’)”;
mysql_query($query);

echo “<script type=’text/javascript’>\n”;
echo “alert(‘you are Succesflly registered’);\n”;
echo “</script>”;

mysql_close();
?>

save this file as insert.php.

3-Put this both file in single Folder and Put this folder in Wamp installation directory, inside  WWW folder

defalut path is =C:\wamp\www\

4- Now again  do right click and click on local host . Main Page of wampserver will open.

On bottom left of project you will find directory in which we store both file. Click on that folder




Our index.html page will open
It will  Look Like this—>

Now Enter the details and and Submit it. Message box will come that you successfully insert data in database , in that way you can try for delete and modify operation.

PHP-Tutorial-for-Beginners-How-to-Get-Started-with-PHP1

PHP Tutorial for Beginners

PHP is a powerful scripting language that fits gracefully into HTML and puts the tools for creating dynamic websites in the hands of the people — even people like me who were too lazy to learn Perl scripting and other complicated backend hoodoo.

This tutorial is for the person who understands HTML but doesn’t know much about PHP. One of PHP’s greatest attributes is that it’s a freely distributed open-source language, so there’s all kinds of excellent reference material about it out there, which means that once you understand the basics, it’s easy to find the materials that you need to push your skills.

Contents

  1. Introduction
    1. What Is PHP?
  2. What you’ll need
  3. Steps
    1. The Basics
      1. Basic Syntax
      2. Code Syntax
    2. Your First Script
    3. Error Messages
    4. A Few More Statements
    5. Very Able Variables
      1. Naming Variables
    6. HTML Forms and PHP
      1. Get versus Post
    7. Arrays
    8. Associative Arrays
    9. Operators; If, Else, Elseif; Loops
      1. If
      2. Else
      3. Elseif
    10. Comparison and Logical Operators
      1. Comparison Operators
      2. Logical Operators
      3. Aritmetic Operators
    11. Loops
      1. Other Loops
    12. Functions
    13. Some Final Thoughts
  4. Suggested readings

Introduction

What Is PHP?

So, what is this whole PHP business all about?

PHP is a program that gets installed on top of your web server software. It works with versions of Apache (Tutorial:Apache for Beginners), Microsoft IIS and other server software packages.

You use PHP by inserting PHP code inside the HTML that makes up your website. When a client (anybody on the web) visits a web page that contains this code, your server executes it. That’s why you need to install your own server in order to test PHP locally — the server is the brain here, not your browser. Users don’t need any special plug-ins or anything to see your PHP in action — it gets to the end user as regular old-fashioned HTML.

PHP is a scripting language, like HTML. That means that code does not need to be compiled before it gets used — it gets processed on the fly as necessary.




Before we dig in, you should know about a site called PHP.net. PHP is an open-source language, and PHP.net is its control center, with extensive reference material about the language and tips sent in by users across the globe. PHP.net has exceptional, deep information about the language, but it can be a little cryptic for the newcomer. We’ll look more closely at how to use PHP.net at the end of this tutorial.

So, what kinds of things can PHP do? Welllll … it can:

  • take info from web-based forms and use it in a million ways (store it in a database, create conditional pages depending on what the forms said, set cookies for later, send e-mail, write your mom on her birthday);
  • authenticate and track users;
  • run threaded discussions on your site;
  • serve different pages to people using different browsers or devices;
  • publish an entire website using just a single layout template (server-side includes-style);
  • serve XML pages.

But before we can get to the specific uses of PHP, we need to start with a quick preview of the building blocks of PHP, beginning with a sample script. This example script is titled “chickenman.php.” When called by a web browser, it would simply read, “I am the CHICKEN MAN!”

1 <?php
2
3
4
5  print ("I am the CHICKEN MAN");
6
7
8
9  ?>

The  ?php and tags start and end a PHP script, and your meat goes in the middle. Got that? Good! Now let’s walk through the basic rules you need to know to before you can write your first PHP script.

What you’ll need

Before we begin, you will need to install a server on your own machine in order to test your PHP scripts locally. You can install WampServer for Windows machines from http://www.wampserver.com/en/ In order to have a Localhost machine. If you’re using a Mac you can get MAMP from http://www.mamp.info.

If you have space on a web server which supports PHP, you can also test your PHP there, but this is kind of a pain because it means you’ll need to FTP your files or telnet in every time you want to change something.

Steps

The Basics

The code itself fits right inside a page’s HTML, and like HTML it is made up of plain ol’ text. So a page that displays the words “I am the CHICKEN MAN!” message would sit inside an HTML page namedsomething.php, like this:

01 <html>
02  <head>
03  <title> Chicken Man Example </title>
04  </head>
05  <body>
06  <font color="red">My PHP code makes this page say:</font>
07  <p>
08  <?php
09  print ("I am the CHICKEN MAN");
10  ?>
11  </p>
12  </body>
13  </html>

See how that works? The HTML is rendered as regular HTML, but everything inside the  ?php and tags gets processed as PHP.




Basic Syntax

It’s time to write your own first PHP script. The basic rules of PHP are as follows:

Naming Files In order to get a PHP script working, the file it’s in or the file that it calls to do the heavy lifting must end in .php (earlier versions used the file extensions .php3 and .phtml). Like HTML, your files are saved as plain text.

Comments It’s important to get in the habit of leaving notes about your code with the comment tags so that months down the road you can make sense of what you were trying to make your script do. The way you set comments apart from your code (that you don’t want displayed or executed) is with either “//” at the beginning of each line, or surrounded by “/*” and “*/” if you want to comment out several lines:

01 <?php
02
03 // This will be ignored. Note to self:
04
05 // Pick up ice cream, cake, and balloons.
06
07 print ("I am the CHICKEN MAN");
08
09 /*
10
11 This, too, will be ignored.
12
13 Hey, and don't forget
14
15 the spanking machine!
16
17 */
18
19 ?>

Code Syntax

Start of Code Every piece of PHP code begins with “<?php” (or the abbreviated “<?” if your server is configured to handle that).

End of Code The way to signify that the PHP code is finished is by adding “?>” at the end.

Every Chunk With a few exceptions, each separate instruction that you write will end with a semicolon.

Parentheses The typical function looks like this …

1 print ( );

… where “print” is the function and the stuff that the function works on sits inside the parentheses, with a semicolon to finish it off. (Just to confuse you, “print” is the exception that also works without parentheses.) By the way, echo () is the same as print ().

Much like HTML, the actual formatting of your PHP code (where you put spaces, line breaks, etc.) will not affect the outcome except those parts of the code that tell a web browser how to display your page. So this piece of code …

01 <?php
02
03
04
05     print ("I am the CHICKEN MAN");
06
07
08
09     ?>
10
11
12
13 ... is effectively identical to:
14
15
16
17     <?php print ("I am the CHICKEN MAN"); ?>

Like more complicated HTML, it behooves you to use white space and tabs in your code to make the code more understandable.

Ready to write your first script? Let’s go.

Your First Script

OK, so write your first script already! Copy the following script, but put whatever you want inside the quotation marks. “Print” here means print to the screen of a web browser when you open the file:

01 <html>
02
03 <body>
04
05   <?php
06
07   print ("I am the CHICKEN MAN");
08
09   ?>
10
11 </body>
12
13 </html>

Save the file with any name that has no spaces and ends in .php, and if you’ve installe

    d a server on your own machine, you need to save the script somewhere inside the server’s root folder (on Windows this is typically in the “wwwroot” directory inside the “inetpub” directory on your C: drive).

The next step is to open the file in your browser. Since you need the server to run your PHP code, you have to open the file through a URL that finds the correct file through your web server. On Windows, your computer name is your root URL. My computer name is “rocketboy,” so to see the contents of my root directory, I type “http://rocketboy” into the Web browser and voila! I see the contents of my root folder. To open the file “chickenman.php” in a directory called “tests” inside the root directory, I’d type “http://rocketboy/tests/chickenman.php” and see my example.

If you’re testing on a PHP-able web server, FTP your files anywhere on your server and they should work when you open them through the URL.

Go on now and get your first script working. Then come back and we’ll have some fun. Together. (If you can’t get your first script working, look at our First Script Troubleshooting Guide.)

Error Messages

Fun, eh? Fun if it worked. If not — if you had an error in your script — you probably got an error message that looked something like this:

1 Parse error:
2
3 parse error in C:Inetpubwwwrootwebmonkey_articletest9.php
4
5 on line 12

Error messages can be very useful and you’re bound to run into lots of them. You’ll get a message like this for every line in your script that has an error. For our purposes, all we really need to know is that there is something wrong with our code in line 12 of the document “test9.php,” so let’s look at that line and see if we can figure it out (good text editors like BBEdit have a function that lets you jump to any particular line). I always start by looking to see if my basic syntax is correct: did I leave out the closing tag, a line’s semicolon, quotation marks?

A Few More Statements

Let’s continue by adding to your test code from the last page to show a couple useful tools.

In the same code that you wrote before, drop in a couple more statements. As you see, you can gang up more than one PHP function inside the same opening and closing tags. My comments in the code explain what each part does:

01 <html>
02
03  <body>
04
05  This text right here (or any HTML I want to write)
06
07  will show up just before the PHP code stuff.
08
09  <p>
10
11  <?php
12
13  // first, this $PHP_SELF thang is
14
15  // an environment variable that'll show the
16
17  // path from your root folder to this
18
19  // document itself, like /webmonkey_article/test3.php.
20
21  // I put this in just for fun.
22
23  // NOTE: This may only work if your server is Apache.
24
25  print "$PHP_SELF";
26
27  // next we have to "print" any
28
29  // HTML code we want the browser
30
31  // to follow to determine
32
33  // the layout of the results page.
34
35  // In this case, we're adding a <p> tag
36
37  // the <p> tags could have been put
38
39  // inside the same print statement as the
40
41  // "I am the CHICKEN MAN" text.
42
43  // between the $PHP_SELF text and the
44
45  // next bunch of stuff.
46
47  print ("<p>");
48
49  print ("I am the CHICKEN MAN");
50
51  print ("<p>");
52
53  /* This next "phpinfo" business outputs a long page that
54
55  tells you exactly how your version of PHP is configured.
56
57  This can be useful when troubleshooting problems down
58
59  the road */
60
61  phpinfo();
62
63  ?>
64
65  </p>
66
67  </body>
68
69  </html>

NOTE: Phpinfo will output a long page of info about your version of PHP. You don’t need to understand what it all means, I just wanted to show you that it’s there if you ever need it.

Very Able Variables

So far, all we’ve done is have a PHP script print some text. Big whoop. Let’s get down and dirty now with variables. A variable is a container for holding one or more values. It is the means by which PHP stores information and passes it along between documents and functions and such. You may remember variables from algebra — in the equation “x + 2 = 8″, x is a variable with the value 6.

The reason why variables are so important to PHP is that the very notion of having dynamic web pages — pages which respond somehow to user input — relies on data being passed around between pages (or parts of a page). Variables are the main mechanism for transferring data like this.

I think the easiest way to explain how variables work in PHP is to show them in action. There are three basic things you can do with variables:

  1. Set them (give them one or more values);
  2. Re-set them if they were set before;
  3. Access them (read the value of a variable and then do something useful with it).

Variables in PHP start with a dollar sign (“$”). Below I am setting a variable, using it, then setting and using it again. The value that a variable holds can be changed any time at all.



01 1. <?php
02
03 2. $utterance = "I love you!";
04
05 3. print ("When I'm happy, I want to say $utterance");
06
07 4. print ("<p>");
08
09 5. $utterance = "I will smite you!";
10
11 6. print ("When I'm angry, I want to say $utterance");
12
13 7. ?>

Here’s what that page will look like:

PHP_Tutorial_utterance.gif

In line two I have created a variable that I decided to name “utterance.” All variables start with “$”, so my variable is written “$utterance” in the code. Here’s how that last code snippet breaks down line by line. Please note: the webserver does the PHP interpreting before sending the browser finished HTML code.

  • Line 1 tells the webserver: “Start PHP code here”.
  • Line 2 creates the variable $utterance and also sets it, giving it the initial value of “I love you!”.
  • Line 3 prints a phrase that draws on the variable $utterance.
  • Line 4 creates atag in HTML to put vertical space between the two utterances.
  • Line 5 RE-SETS the variable $utterance and gives it the value “I will smite you!”.
  • Line 6 prints a new phrase that draws on the new meaning of the variable $utterance.
  • Line 7 tells Mr. Webserver: PHP code ends here.

See how the variable $utterance is used as a sort of container that can hold different values? We just set and then called variables inside the same script, but the power of PHP is that you can set a variable in one place — say from a form that a user fills out — and then use that variable later.

The syntax of setting a variable is to:

  • define it with the = sign ($utterance = “I love you!”;);
  • use quotation marks if you’re defining it with a string of letters (“I love you!”; numbers don’t require quotes);
  • end each instruction with a semicolon.

Then you call it by refering to the variable name ($utterance in lines 3 and 6 — notice no quotation marks there).

Naming Variables

You can name a variable anything you want so long as it follows these rules:

  • it starts with a letter;
  • it is made up of letters, numbers, and the underscore character (that’s the _ character, as in “$baby_names”);
  • it isn’t used elsewhere (like “print”).

Warning: Variable names are case-sensitive, so $baby_names and $Baby_names are not the same. You also should try to make your names have some meaning so that you can still make sense of your code next year.

In the examples so far, we have set variables as chunks of text, which are known as “strings.” Variables can also hold the values of numbers and some other things as well (objects, arrays, booleans).

Final note: One thing that can be a little confusing when starting to use PHP is the use of quotation marks inside PHP functions. Use single or double quotes to set off strings (that is, chunks of text), as in:

1 print ("I am the CHICKEN MAN");

This will print the text I am the CHICKEN MAN. If you want to display quotation marks as characters in the output of your PHP script, you must escape them with the “” character, which tells PHP not to use the next character as part of the code. So to output the text “I am the CHICKEN MAN” (with quotation marks showing in the result) the code would look like:

1 print (" "I am the CHICKEN MAN"" );

HTML Forms and PHP

In our examples so far, we have set variables and then used them all in the same code. This doesn’t make much sense because in those instances, we could have just hard-coded the values instead of using variables.

Let’s get some real mileage by creating HTML forms to gather user input, turning that input into variables, and then doing various things with the information that we just collected.

No sense in sitting around waiting – let’s go ahead and make a Web page that collects your favorite dirty word and displays it on another page that tells you what a pervert you are. All of this gives a page that looks a lot like this.

First, we make the form page, which is regular HTML with a form in it. I’m calling mine “badwords_form.html,” but call yours whatever you like. (If you want a good primer on HTML forms, read Jay’s How To Add HTML Forms to Your Site tutorial.)

01 <html>
02
03  <head>
04
05  <title>My Form</title>
06
07  </head>
08
09  <body>
10
11  <form action="bad_words.php" method=post>
12
13  My name is:
14
15  <br> <input type="text" name="YourName">
16
17  My favorite dirty word is:
18
19  <br /><input type="text" name="FavoriteWord">
20
21  <input type="submit" name="submit" value="That's Right!">
22
23  </form>
24
25  </body>
26
27  </html>

This is a regular HTML form. The important pieces are as follows:

Line 7: the HTML that reads action="bad_words.php" tells the browser which PHP document will process the results of the form. That is to say, in a minute you’ll create a document called “bad_words.php” which will be the little engine that makes the result page happen. (We’ll get to themethod=post part later on.)

Line 10: input type="text" determines that the form element which we want here is “text” or a text box (we could also have a radio button, check box, etc.); name="YourName" determines that whatever the user types into the text box will become a variable that we have called “YourName.” This is what ties together forms and variables – each form field can set a variable to be used however you want.

Line 13: here you have another text input that sets a variable called “FavoriteWord” which is the user’s favorite dirty word.

Line 16, 17: This code makes a submit button with the text “That’s Right!” and ends the form.

So this form will collect the unassuming user’s name and favorite bad word, but now what do we do with it? Let’s take the variables she set and echo them back in another context on another page.

On line 7 of the HTML above, we told the form to head on over to bad_words.php once the submit button was hit. This is what bad_words.php looks like:

01 1.
02
03 2.
04
05 3.
06
07 4.
08
09 5.
10
11 6.
12
13 7.
14
15 8.
16
17 9.
18
19 10.
20
21 11.
22
23 12.
24
25 13.
26
27 14.
28
29 15.
30
31 16.
32
33 17.
34
35 18.
36
37 19.
38
39 20.
40
41 21.
42
43 22.
44
45 23.
46
47 24.
48
49 25.
50
51 26.
52
53 27.
01 <html>
02
03 <head>
04
05 <title>Perv!</title>
06
07 </head>
08
09
10
11 <?php
12
13 // Capture the values posted to this php program from the text fields
14
15 // which were named 'YourName' and 'FavoriteWord' respectively
16
17
18
19 $YourName = $_REQUEST['YourName'] ;
20
21 $FavoriteWord = $_REQUEST['FavoriteWord'] ;
22
23 ?>
24
25
26
27 <body bgcolor="#FFFFFF" text="#000000">
28
29 <p>
30
31
32
33 Hi <?php print $YourName; ?>
34
35
36
37 <p>
38
39
40
41 You like the word <b> <?php print $FavoriteWord; ?>!?!</b>
42
43
44
45 <p>You oughta be ashamed of yourself!
46
47
48
49 </body>
50
51
52
53 </html>

See how this form passed a variable along from the form page to the PHP file? You have not seen the last of this.

Get versus Post

So far, we’ve used the “Post” method of passing form data as opposed to the other method, “Get.” This is the part of the form code that reads  form action="bad_words.php" method=post¢.

The difference between these two is that the “post” method transparently passes along all the information the page has gathered, whereas the “get” method will pass all that info along as part of the URL (in the form above, this would look like: http://rocketboy/webmonkey_article/bad_words.php?YourName=bob&FavoriteWord=crikey%21&submit=Enter+My+Data%21 – see how the info the user entered about his name and his favorite word get added to the URL?)

Arrays

One of your best tools now that you’ve mastered variables – you have, haven’t you? – are arrays.

Arrays give you the ability to store not just one value inside a variable, but a whole bunch of values in a single variable.

If I wanted to catalog all of the animals in my house, I could set each one as a regular variable. I’ve got two dogs, Phoebe and Ruby, and a squirrel that died in the attic last year, whom we’ll call Rotty. Setting each one as a variable looks like this:

1 $dog1 = "Phoebe";
2
3 $dog2 = "Ruby";
4
5 $squirrel1 = "Rotty";

But an array will let us store all these inside one single variable, which I’ll call $critters. Each element of the variable has its own “key” that is used to access that part of the array, which can either be a string of letters or numbers.

Let me explain the “key” concept another way: If we’re storing three different values inside one variable (like storing Phoebe, Ruby, and Rotty inside $critters), we need some way to be able to suck out any individual part of the array to use it. An array will automatically number each element that comprises it, so the key can be element 1, element 2, and element 3. Or, as we’ll see later on, we can name each part of the array with text. In this case I could make the keys “fat dog,” “skinny dog,” and “squirrel” and use those to identify each array member.

Let’s make a simple array and then use it. The easiest way to create an array is to use the array() function, which assigns a bunch of values to your array at once and looks like this:

1 $critters = array ( "Phoebe", "Ruby", "Rotty" );

This stores all my animal names into one variable ($critters) in an array, and automatically assigns a numbered “key” to each element starting in order and giving the first element the number 0. So Phoebe is element [0], Ruby is [1], Rotty is [2], etc. I make up the name of the array myself (here it’s $critters).

You can now get at any of the array elements by referring to the variable followed by the element number in square brackets: $critters[0], for example. Here it is in action:

1 <?php
2
3
4
5     print "$critters[2]";
6
7
8
9     ?>

This will simply print the third element in the array, which is Rotty (don’t forget that array numbers start at 0, so $critters[2] is third after $critters[0] and $critters[1]).

There’s another way to set an array, or even to add to an existing array, by setting each element individually:

1 $critters[] = "Phoebe";
2
3    $critters[] = "Ruby";
4
5    $critters[] = "Rotty";

This’ll have the same effect as using the array() function, giving the first element the key [0] and so on. But wait! I forgot about Opie the cat. Hmmm. Regardless of how we made the array in the first place, I can easily add Opie like this:

1 $critters[] = "Opie";

PHP is smart enough to count the number of elements and give Opie the next available one, which in this case (after Phoebe, Ruby, and Rotty) is [3].

To recap this concept, I can set an array to include the animals in my house either this way:

1 $critters[] = "Phoebe";
2
3 $critters[] = "Ruby";
4
5 $critters[] = "Rotty";
6
7 $critters[] = "Opie";

Or this way:

1 $critters = array ( "Phoebe", "Ruby", "Rotty", "Opie" );

Both will be indexed in the computer brain with the values:

1 $critters[0] = "Phoebe";
2
3 $critters[1] = "Ruby";
4
5 $critters[2] = "Rotty";
6
7 $critters[3] = "Opie";

And in both cases, you could get at any element in the array by describing its number …

1 <?php
2
3
4
5    print "$critters[3]";
6
7
8
9    ?>

… which would print the string Opie to the window of your browser.

Arrays can be made to do all kinds of things, like being incremented by number, sorted in alphabetical order, printed by different types of categorization, and many more.

Associative Arrays

Ready to get more complicated? The associative array indexes the contained elements not by numbers, but by names that you determine. Inside the array() function, you set up pairs where you name the key and its value using the combo of the “=” and the “>”, like: key=>”value”. Here’s what it looks like in action:

01 $PhoebeDog = array (
02
03           name=>"Phoebe",
04
05           description=>"fat dog",
06
07           color=>"grey and white",
08
09           age=>7
10
11               );

Here we’re telling the array to create the keys “name,” “description,” “color,” and “age”; and we give each of those keys a value (name is “Phoebe”, description is “fat dog,” and so on).

We can get at any part of the array through the “key” names that we set, for example:

1 print $PhoebeDog[color];

will give us grey and white. We can also set each key individually, like so:

1 $animals[name] = "Phoebe";
2
3 $animals[description] = "fat dog";
4
5 $animals[color] = "grey and white";
6
7 $animals[age] = 7;

Finally, let’s make it hurt. We’re going to get some serious power out of this arrays business by creating a “multi-dimensional” array. A multi-dimensional array is an array (say the animals in my house) that is made up of other arrays (for each animal, an array that contains the critter’s name, color, description, and age).

We make multi-dimensional arrays by creating one array:

1 $animals = array
2
3         (
4
5             );

…and then we fill that array with an array of animals in which we’ve defined the keys, like this:

01 $animals = array (
02
03         array ( name=>"Phoebe",
04
05                 type=>"dog",
06
07                 color=>"grey and white",
08
09                 age=>7 ),
10
11         array ( name=>"Ruby",
12
13                 type=>"dog",
14
15                 color=>"brown and white",
16
17                 age=>7 ),
18
19         array ( name=>"Rotty",
20
21                 type=>"squirrel",
22
23                 color=>"grey",
24
25                 age=>2 ),
26
27         array ( name=>"Opie",
28
29                 type=>"cat",
30
31                 color=>"grey tabby",
32
33                 age=>5 )
34
35                     );

To use this now, we can get any part of the information contained in there by naming the overall array ($animals), naming the number of the sub-array that we want to find out about (Phoebe is [0], Ruby is [1], etc.) and then naming the key for the attribute we want to get at (name, type, color, or age).

To find out the age of the cat, we’d write:

1 print $animals[3][age];

Here’s what it all looks like together. This is all in one page, but remember that you can set arrays in one place (in code or in form fields from another page or in a database, say) and get at the info contained within from somewhere else. Here I’m putting it all together on one page so you can see it all at once.

01 <html>
02
03 <head>
04
05 <title>Pet Arrays</title>
06
07 </head>
08
09
10
11 <body>
12
13
14
15 <?php
16
17
18
19 $animals = array (
20
21         array ( name => "Phoebe",
22
23                 type => "dog",
24
25                 color => "grey and white",
26
27                 age => 7 ),
28
29         array ( name => "Ruby",
30
31                 type => "dog",
32
33                 color => "brown and white",
34
35                 age =>7 ),
36
37         array ( name => "Rotty",
38
39                 type => "squirrel",
40
41                 color => "grey",
42
43                 age =>2 ),
44
45         array ( name => "Opie",
46
47                 type => "cat",
48
49                 color => "grey tabby",
50
51                 age => 5 )
52
53                     );
54
55
56
57 print $animals[2]["type"];
58
59 print ("<br>");
60
61 print $animals[3]["color"];
62
63
64
65 ?>
66
67
68
69
70
71 </body></html>

What we’ve just done is create an array that includes a sub-array for each animal which contains detailed info about that critter; then we print a sentence that uses the type and ages of two of the animals.

Operators; If, Else, Elseif; Loops

The whole deal about making dynamic websites is that you want your web page to be as smart as possible — to have code sitting there that can make all sorts of decisions based on different kinds of user input, user conditions (what browser is Visitor X using?), or information that you set yourself. Examples of this could be:

  • After a user enters an email address, check that it has a valid form (whoever@wherever.com) and if not, serve a page that says, “hey pal, how about a VALID email address?”
  • Serve one set of HTML to .com domains and another to .gov domains (where you try not to use any big words that might confuse ‘em).
  • Know whether a customer at your online store is meeting a minimum dollar amount for an online credit card purchase.
  • And on and on and on – the possibilities are limitless.

If

The way to make your pages smart is to use If, Else, and Elseif statements along with Comparison and Logical Operators. The most important one of these is the

1

statement, which gives you the ability to code:

1 If some condition is true, then do somesuch thing;
2
3 If the condition is not true, then ignore it;

The syntax of this statement is as follows:

1 if (condition) {
2
3
4
5 // code in here to execute if the condition is true
6
7
8
9 }

Here it is in action. First we set the variable

01 <?php
02
03
04
05  $FavoriteColor = "blue";
06
07
08
09  if ($FavoriteColor == "blue") {
10
11
12
13  print ("I like blue too!");
14
15
16
17  }
18
19
20
21  ?>

Please note that:

1 if ($FavoriteColor = "blue")

and

1 if ($FavoriteColor == "blue")

are not the same thing, the first will always be true as it sets $FavoriteColor to blue.

Else

Else builds on the if statement as if to say:

1 If some condition is true, then do somesuch thing;
2
3 ELSE, in case that first condition is NOT true, then do this other thing.

It works like this:

01 if (condition) {
02
03
04
05 // code in here to execute if the condition is true
06
07
08
09 } else {
10
11
12
13 // code in here to execute if the condition is not true
14
15
16
17 }

Here it is in motion:

01 <?php
02
03
04
05 $FavoriteColor = "yellow";
06
07
08
09 if ($FavoriteColor == "blue") {
10
11
12
13 print ("I like blue too!");
14
15
16
17 } else {
18
19
20
21 print ("You don't like blue?! Crazy fool!");
22
23
24
25 }
26
27
28
29 ?>

What you see above is the typical format for writing statements like this. The key part is to see where the curly braces are so you don’t get confused as to which statement belongs to which piece of the code. Above, the first set of { and } belong to the “if,” the second { and } belong to the “else.”

Elseif

There’s one more sibling in the if, else family, and it’s called elseif. Where else is sort of a blanket control that make something happen as long as the if statement is not true, elseif makes something happen if a specific condition is met:

1 IF some condition is true, then do somesuch thing;
2
3     ELSEIF some other specific condition is true, then do another thing;

It looks like this:

01 <?php
02
03
04
05     $FavoriteColor = "green";
06
07
08
09     if ($FavoriteColor == "blue") {
10
11
12
13     print ("I like blue too!");
14
15
16
17     } elseif ($FavoriteColor = green) {
18
19
20
21     print ("MMMmmmmmmmmmm, green!");
22
23
24
25     }
26
27
28
29     ?>

You could even add an ELSE statement at the end in case FavoriteColor were neither blue nor green.

Comparison and Logical Operators

We’ve seen how the “=” sign works when we set variables in the scripts we’ve written so far (as in the code$FavoriteColor = "blue"; and $utterance = "I will smite you!"; ). The equal sign here is what we call the “assignment operator” and is the simplest operator we’ve got: $a = b means “the variable a is assigned the value b (for the moment).”

But you can squeeze a lot more juice out of your PHP using what are called “comparison operators,” “logical operators,” and “arithmetic operators.” Here’s what they are, in tables copied verbatim fromPHP.net.

Comparison Operators

These give you the ability to compare whether elements are equal, identical, less than or greater than one another (with some other variations).

Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (PHP 4 only)
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (PHP 4 only)
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

Logical Operators

Here you can compare elements using comparisons and, or, and the like.

Example Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
 ! $a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.

Aritmetic Operators

Just what it says – this is basic math.

Example Name Result
$a + $b Addition Sum of $a and $b.
$a – $b Subtraction Difference of $a and $b.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Quotient of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.

Loops

Loops are really handy. They let you program your code to repeat itself (and also to figure out how many times to run through itself before it’s done). Loops have instructions to “keep running this piece of code over and over again until certain conditions are met.” You can use more than one kind of loop. Let’s look at the most basic kind, the “while” loop.

The while loop says,

01 while (something is true)
02
03
04
05 {
06
07
08
09 // do something that you specify
10
11
12
13 }

While loops are often used with incrementing and decrementing a variable that is an integer. What in thehell does that mean? It means that you can automatically have the script add (or subtract) a whole number (1, 2, 3, etc.) from part of a script each time it runs through, until the number reaches a maximum or minimum value that you’ve set.

So if you wanted a script to print the numbers from 1 to 10, you can tell it (this is English, not PHP here):

01 a. the variable $MyNumber = 1;
02
03
04
05 b. print $MyNumber;
06
07
08
09 c. add 1 to $MyNumber;
10
11
12
13 d. go to sep a. and run this script again with the new value of $MyNumber;
14
15
16
17 d. stop when $MyNumber reaches 11;

The syntax for incrementing and decrementing the value of a variable is:

$a++; adds 1 to the value of the variable $a each time through
$a–; subtracts 1 from the value of the variable $a each time through

So the code itself for printing the numbers 1 through 10 could look like this:

01 1.
02
03 2.
04
05 3.
06
07 4.
08
09 5.
10
11 6.
12
13 7.
14
15 8.
16
17 9.
18
19 10.
20
21 11.
22
23 12.
24
25 13.
26
27 14.
28
29 15.
01 <?php
02
03
04
05 $MyNumber = 1;
06
07
08
09 while ($MyNumber <= 10)
10
11
12
13 {
14
15
16
17 print ("$MyNumber");
18
19
20
21 $MyNumber++;
22
23
24
25 }
26
27
28
29  ?>
  • line 1: start PHP code;
  • line 3: set variable $MyNumber to 1;
  • line 5: initiate “while” loop: while the variable $MyNumber is less than or equal to 10, execute what’s below; otherwise move on;
  • line 9: print the current value of $MyNumber;
  • line 11: add 1 to the value of $MyNumber;
  • line 15: end PHP code.

For these loops, you can use all the “operators” listed on the section above to be the conditions that must be met before the loop stops.

Other Loops

PHP has other kinds of loops, but they are beyond the scope of this tutorial. If you want to learn what they are and how to use them, follow these links to PHP.net:

Functions

If you’ve used HTML a lot, you know that it’s a pretty limited language that was designed back in the dark ages before we all knew what the Net was capable of.

PHP, however, is very flexible. Not only does PHP have a library of canned functions that’ll do everything from sorting stuff in alphabetical order to sending email, from connecting with databases to balancing your spaceship’s inertial sub-space dampers, but you can also create your very own functions to do all manner of things related to your website. The functions you create get executed exactly like those from the PHP library, but they’re your own. In the following section, I’ll show a glimpse of how you create your own functions and feel the power.

Functions you create are like little machines that do something for you. You construct them and then call them as needed.

You’ll remember that the very first thing we learned to do was a simple “print” statement, which followed the form:

1 <?php
2
3
4
5  print ("whatever it is I want to show up on-screen");
6
7
8
9  ?>

Functions that you create are built upon a similar form, but take it farther:

01 <?php
02
03
04
05 function MyFunction ()
06
07
08
09 {
10
11
12
13 statements that make up the function;
14
15
16
17 }
18
19
20
21 ?>

So you start a function with the words function WhatYouNameIt(), with the words WhatYouNameIt() being anything you choose (no spaces).

Then you define the rules of the function inside the following curly brackets (that’s { and } on lines 5 and 9). Don’t you just love the words “curly brackets?”

Let’s walk through the making of a couple functions. Functions come in two flavors, those that require “arguments” and those that don’t. An “argument” is a variable that comes from outside the function, but which the function needs in order to run.

Let’s first look at one that doesn’t require arguments:

01 <?php
02
03
04
05 function ChickenMan()
06
07
08
09 {
10
11
12
13 print "<b>I am the CHICKEN MAN!</b>";
14
15
16
17 }
18
19
20
21 ChickenMan();
22
23
24
25 ?>

line 1: start PHP;
line 3: create function ChickenMan;
line 5: start definition of function ChickenMan;
line 7: definition of ChickenMan is to print “I am the CHICKEN MAN!” inside and tags;
line 9: end definition of ChickenMan;
line 11: call function ChickenMan (meaning “do the thing that we defined the function to do”);
line 13: close PHP;

Any place in this web page that you put “ChickenMan();” inside the <?php and ?> tags, it’ll print your little statement. See how this saves you time if you want to print this string a bunch of times in different places?

Now let’s get a little more complicated and create a function that does take arguments. Say I’m a loan shark and I’m going to loan you the money to buy that personal hovercraft you’ve been lusting after. I’ll lend you however much you need, but you have to pay me 14 percent interest per week or I break your legs.

I’ll create a function called InterestPayment which calculates your weekly payments (until you pay off the whole loan amount in one lump sum).

First we’ll create a form page where the user enters how much of a loan he or she wants. The user enters the hovercraft’s sticker price, and that number gets passed along from the form as a variable called  font size="2">$Cost. (For the HTML behind this, go here.)

Next, our function will take the amount that the user enters into the variable  font size="2">$Cost and spit back 14 percent of that amount, which is how much the hapless borrower owes every week. This will happen in the PHP page titled “loanshark.php” that the form page points to (it points with this code: <form action=”loanshark.php” method=post> ). Here’s what the function will look like:

01 1.
02
03 2.
04
05 3.
06
07 4.
08
09 5.
10
11 6.
12
13 7.
14
15 8.
16
17 9.
18
19 10.
20
21 11.
22
23 12.
24
25 13.
26
27 14.
28
29 15.
30
31 16.
32
33 17.
34
35 18.
36
37 19.
38
39 20.
40
41 21.
42
43 22.
44
45 23.
46
47 24.
48
49 25.
50
51 26.
01 <html>
02
03  <head>
04
05  <title>Loans</title>
06
07  </head>
08
09
10
11  <body>
12
13
14
15  <?php
16
17
18
19  $interest_rate = .14;
20
21
22
23  function YouOweMe($cost, $interest_rate) {
24
25
26
27  $weekly_payment = ($cost*$interest_rate);
28
29
30
31  print "You better pay me $$weekly_payment every week, or else!";
32
33
34
35  }
36
37
38
39
40
41 <font color="#000000">YouOweMe($cost, $interest_rate);
42
43
44
45  ?>
46
47
48
49
50
51  </body>
52
53  </html>

Here’s the line-by-line breakdown.

line 8: start php;
line 10: set variable called $interest_rate to 14%;
line 12: create function YouOweMe that relates to the variables $cost and $interest_rate;
line 14: create variable $weekly_payment, the value of which is the cost times the interest rate;
line 16: print to screen a sentence that uses the value of the $weekly_payment variable;
line 20: engage the function YouOweMe, which (because of the function defined beforehand) simply prints the sentence You better pay me [14% of the amount the user entered on the form page] every week, or else!

Notice on line 16 that we want the code to actually print out a dollar sign before the weekly payment. We escape that character with a to make sure the PHP engine doesn’t think we’re naming a variable there. Then we just happen to name a variable right afterwards ($WeeklyPayment), so the two together look like font size="2">$$WeeklyPayment.

Some Final Thoughts

If it got a little brutal back there trying to make sense of my functions, don’t worry — you’ll probably get used to squinting through other people’s code once you get going. That’s because somebody has probably written code for whatever you need to do already, and is probably happy to share it with you. Making sense of it all gets easier and easier the more you use this stuff. And since PHP is an open-source language (meaning the source code is shared openly instead of being hoarded by an evil corporation), the language is surrounded by a sense of cooperation among its users, many of whom will help you if they can.

Suggested readings

With the knowledge that you have so far, you can go almost anywhere with this PHP business. But how do you find out out to do a particular task that you need to do? Here are some good resources. These are just places that I frequent, but by no means is this a comprehensive list:

  • PHP.net: As I’ve mentioned, PHP.net is the language’s central brain. Here are parts of PHP.net that I’ve found especially useful.
  • Manual: The site contains a general manual for PHP. Some functions may take a while to figure out, but it’s all here. Once at PHP.net, follow the links to Documentation > View Online and pick your language.
  • Function List: At the top of the main php.net page you’ll find a search box in which you can search different areas of the site. If there’s a function you need to find, search through the functions there. Often you’ll have to search for a word (“cookie”) and then figure out from the results which function is what you want (“setcookie”).
  • FAQ: Find great info in the FAQ, including a category titled “Common Problems.”

TIP: No matter what source you use for reference material (and you’ll need sources!), there’s a general rule of thumb to use when writing this stuff. It’s always good to map out what you need to do and then test your concept as simply as possible. Once you get the machinery working, you can put in your real content and make it more and more complex. It’s much harder to troubleshoot if you don’t start out with simple pieces.
Recommended Reading

I bought several books when I started learning PHP that were of varying quality. I really liked Larry Ullman’s “PHP for the World Wide Web” (Peachpit Press). “Teach Yourself PHP4 in 24 Hours” by Matt Zandstra was also good. Books published by O’Reilly are also generally excellent.

20160217_php

20 Tips you need to learn to become a better PHP Programmer

PHP is a very versatile programming language that can achieve the same objective in multiple ways. You can read more about that in my ‘The Art of Programming‘ post. Below are a few tips I’ve picked up from past projects that can improve your code readability and maintainability and make you a neater, more organized PHP programmer.

20160217_php

Here you go:

Use <?php and ?>

To start your script, avoid using <? ?>. While these may work on your server, they might not work on another server if you ever decide to run your script elsewhere.




Similarly, when echoing a variable, try to avoid using the shortcut tags as they might not be supported everywhere. I found it pretty hard to stop using them since they save so much space but at the end of day, they do make your code more portable.

1
2
3
4
5
<? ... ?> // Incorrect
<?php ... ?> // Correct
<?=$Var?> // Incorrect
<?php echo $Var ?> // Correct

Separate Configuration Files

There’s no reason you should be adding configuration settings to your script file. Always create a separate file and include that file at the top of your script. The last thing you want is to have to edit each and every page because of a little configuration change. Including a file is super easy:

1
2
3
include("<span class="skimlinks-unlinked">config.php</span>");
// code goes here ...

Comments are your Friend

Yep, I bet you saw this one coming? It’s amazing how hard we find it to understand our own code that has been written a while ago. Comments will help you figure out certain things which seemed obvious at the time. Here’s the syntax:

1
2
3
4
5
6
// Line One Comment
// Line Two Comment
/** Paragraph Comment
Paragraph Comment
Paragraph Comment **/

Easy, huh?

Use Indentation and Spacing

There’s nothing much worse than having to modify somebody’s code and realizing nothing has been indented properly. Having well indented code with the right spacing immediately says a lot about you as a programmer. Ideally, you should be able to immediately figure out whether a loop has ended or not by just quickly looking through your code. Here’s an example of badly indented code:

1
2
3
4
5
function  dothisformula($a,$b) { $c = $b+$a;
     $e=3;
while ($c < 20) {
$e = $e - 1; $c = $c + 1; }
     return $e; }

And here’s the same code, properly formatted:

1
2
3
4
5
6
7
8
9
function dothisformula($a, $b) {
     $c = $b + $a;
     $e = 3;
     while ($c < 20) {
          $e = $e - 1;
          $c = $c + 1;
     }
     return $e;
}

See what a difference some spacing makes?

Give your Variables Meaningful Names

Always give your variables name that mean something to you. Take this one step further by also including some details about what type of data they store. For instance, if we were using a variable as an integer, you could add an i to the beginning of the name. This especially important since we do not specify a type when declaring a variable in PHP.

Choosing whether to have caps or not in your variable name is up to you but it is often recommended to capitalize the first letter of every word in your variable. This makes it easy to read and understand.

Here’s what I use:

1
2
3
4
5
6
7
8
9
10
11
$iNumber = 10; // For Integers
$sName = "Marc"; // For Strings
$fPi = 3.14159265; // For Floats
$aNames = array(); // For Arrays
$oUser = new User(); // For Objects
$bIsMember = false; // For Booleans

Initialize your Variables

Although PHP will automatically create a variable the moment you try to assign a value to it, it is always good practice to initialize your variables before using them. This will make your code much cleaner and make sure your variables are always the type you want them to be:

1
2
3
$aArray = array();
$iInteger = 0;
$bBoolean = false;

Boolean is False, unless True

If you’re checking whether something is a specific value and storing the result in a boolean value, always start off assuming it’s false. For instance, the following code should be avoided:

1
2
3
4
5
function getStatus() {
    $bReturn = true;
    if ($i != 2) $bReturn = false;
    return $bReturn;
}

Instead, you should use:

1
2
3
4
5
function getStatus() {
    $bReturn = false;
    if ($i == 2) $bReturn = true;
    return $bReturn;
}

The second is the ideal solution for when you’re just checking one item. Why? Well, imagine you’re validating some data for a database – If, for whatever reason, your if statement is completely missed, your return value will still be false, therefore avoiding the input of invalid data. Since we frequently deal with sensitive data in PHP scripts, it’s better assuming something should not run until proven otherwise, rather than the other way round. I learned this the hard way.

Ideally, your validation should check what your data should be like, not what it shouldn’t be like.

Using Quotes when accessing Array Keys

When accessing arrays, you might find that the following two lines both work:

1
2
$sName = $aNames['marc'];
$sName = $aNames[marc];

In the second line, PHP is actually first trying to find a constant called “marc” and then converting “marc” to a string once no constant is found. Even though it works, you should avoid using no quotes as if you ever create a constant with the same name, your script would stop working.

Use commas to echo different strings

If you want to output both text and variables in the same string, you can use commas instead of dots. Why? Because it is marginally faster (based on this test).

1
echo "Hello, my name is ", $sName;

Instead of…

1
echo "Hello, my name is " . $sName;

Use Ternary Operators

If you have a simple IF statement, you can use a ternary operator which allows you to do the same thing in one line. Here’s an IF statement:

1
2
if ($a == 1) $b = 2;
else $b = 3;

You can do the same thing using a ternary operator as shown below:

1
$b = ($a == 1) ? 2 : 3;

Easy, right? The ternary operation is basically doing this:

1
$variable = (CONDITION) ? IFTRUE : IFFALSE;

Use === for Boolean Checks

If you’re checking whether a variable is true or false, use === rather than the usual == which we use for comparisons. The three equal signs tell PHP to also check the variable type.

1
2
if ($bIsMember == true) { ... } // Incorrect
if ($bIsMember === true) { ... } // Correct

Use ++ and — Operators

If you want to increase or decrease an integer by 1, you can easily use incrementing and decrementing operators. If you have the following code:

1
2
$iNumber = $iNumber  + 1;
$iNumber2 = $iNumber2 - 1;

This should be converted to:

1
2
$iNumber++;
$iNumber2--;

The great thing about these operators is the way you can use them while completing other actions (for instance, in an if or while statement). Depending on whether you put the or ++ before the variable or after, the operator will run before or after the action is complete. The examples below are all valid uses and will help you understand what I mean:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$iNumber = 10;
while ($iNumber++ == 10) { ... }
// This will run once as the increment operator
// is run after the comparison
$iNumber = 10;
if (--$iNumber == 10) { ... }
// This will not run as the decrement operator
// is run before the comparison
$iNumber = 10;
$iTotal = $iNumber++;
// $iTotal will be 10.
$iNumber = 10;
$iTotal = --$iNumber;
// $iTotal will be 9.

Use Assignment Operators

If you wanted to increase or decrease a variable by more than one, you can easily use assignment operators. Here’s how your code might look:

1
2
3
4
$a = $a + $b;
$a = $a * 5;
$a = $a - $d;
$a = $a / 3;

Using assignment operators, you can instead write:

1
2
3
4
$a += $b;
$a *= 5;
$a -= $d;
$a /= 3;

You can also use this for strings. The following two lines do the same thing:

1
2
$sString = $sString . "hello";
$sString .= "hello";

Create a Variable Dump Function

We’re all familiar with print_r which we constantly use as we’re testing our script and figuring out what value our variables currently have. To make this even simpler, you can create a function such as:

1
2
3
4
5
function p($var) {
    echo "<pre>";
    print_r($var);
    echo "</pre>";
}





This will make sure your variable dump is always enclosed by <pre> tags which are used to make your output much more readable. Additionally, since we can give our function a one letter name, it will be even faster and easier to use.

Use Constants

If you have a variable which never changes, there’s no point constantly re-writing the same thing over and over again. Use constants to define data which you access often like directory paths, error messages etc. I’d recommended giving your constants names which are fully capitalized to help you realize immediately when you’re using them.

1
2
3
define ("DIRECTORY","/path/to/site/");
echo DIRECTORY;

Use $_GET and $_POST

Avoid using $_REQUEST which gets both POST and GET variables. Use $_GET to get parameters from your URL and use $_POST to get variables submitted from a form:

1
2
3
$sAction = $_GET['actions'];
$sName = $_POST['name'];

This will avoid users manually overwriting variables in the URL which you are expecting to receive from a form.

Use Objects instead of Functions

If you function has lots of parameters, it’s time to move over to objects. I’ve worked on projects that got too complex to maintain after a few of the functions ended up having over 20 parameters! The moment you realize you need to modify the way the function is called, you will need to change each and every function call. So, instead of this:

1
2
3
4
function getProducts($iParameter1, $iParameter2,
$iParameter3, $iParameter4, $iParameter5,
$iParameter6, $iParameter7, $iParameter8,
 $iParameter9) { ... }

You can use:

1
2
3
4
5
$oProducts->setParameter1(...);
$oProducts->setParameter3(...);
$oProducts->setParameter5(...);
$oProducts->setParameter6(...);
$oProducts->getProducts();

Use Method Chaining

If you’re doing multiple object method calls that set variables instead your object, you can use method chaining to make your code simpler. To do this, just end each method with return $this; as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
class User {
    function setThis($iVar) {
        ....
        return $this;
    }
    function setThis2($iVar2) {
        ....
        return $this;
    }
}

You will then be able to do method chaining:

1
2
3
$oUser = new User();
$oUser->setThis(...)
      ->setThis2();

That will make your code smaller and neater.

Stop Repeating Code

Don’t repeat any code – If you have a few lines that do the exact same thing, turn them into one function. Or better yet, turn them into an object. Although this might seem like extra work, it will pay off once your application gets bigger and bigger. As a simple example, if you had:

1
2
3
4
5
6
7
8
$a = 1;
while ($a < 10) {
    $b = $a * 10;
    $c = $b * 2;
    $d = $c * $b;
    echo $d;
    $a++;
}

You could write this like this:

1
2
3
4
5
6
7
8
9
10
11
12
function multiply($iVar, $iVar2) {
     return ($iVar*$iVar2);
}
$a = 1;
while ($a < 10) {
    $b = multiply($a, 10);
    $c = multiply($b, 2);
    $d = multiply($c, $b);
    echo $d;
    $a++;
}





This is, of course, a super simple example. This will be especially useful for when you have big portions of code that are repeated.

Aim for Loose Coupling, Strong Cohesion

Coupling is the degree in which the change in one component requires a change in another. In other words, if you change one function, will you need to change another? The looser the coupling, the more you will be able to modify components without affecting others. Cohesion, on the other hand, is the degree in which different parts form a meaningful unit. Does your main function do practically everything or do you have many functions which each do very specific jobs? If you do, then you have a strong cohesion. Strong Cohesion happens when your components have clearly defined responsibilities and call other functions for processing which does not form part of their objective.

As a PHP Programmer, you should always aim to create components (functions, classes…) that are both loosely coupled and have a strong cohesion to increase code maintainability and extensibility. Whenever creating a function, try to keep in mind that you might have to use it in other scenarios. Avoid adding code which is highly dependent on other components being set up correctly. Ideally, you should be able to change a system and any other systems depending on it will continue to work without modification.

If we apply this to code, here’s a simple example:

1
2
3
4
5
6
7
8
9
10
11
12
13
// We want to add two numbers
// only if the first number is
// lower than 5
function add($iVar, $iVar2) {
    if ($iVar < 5) return false;
    else $iResult = $iVar+$iVar2;
    echo "The Result is ", $iResult;
}
$iVar = 3;
$iVar2 = 2;
add($iVar, $iVar2);

The example above is tightly coupled and has weak cohesion since we are doing validation inside the function itself. We are also putting the result output inside the function itself which will be a problem once we have many functions doing the same and we decide to change the text for it.

Here’s a much better version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// We want to add two numbers
// only if the first number is
// lower than 5
function add($iVar, $iVar2) {
    return $iVar + $iVar2;
}
function result($sMessage) {
    return "The Result is " . $sMessage;
}
$iVar = 3;
$iVar2 = 2;
if ($iVar < 5) {
    echo result(add($iVar, $iVar2));
}

We can now re-use both add and result functions anywhere in the code. We can also easily modify their functionality without having to modify any other part of the program.

In Summary

The tips above should help you write neater, shorter and more organized code. The examples above were very simple but should help you understand the basics of each concept. If you do not agree with me on any one of them, please go ahead and comment below. We’re all here to learn. :)

Bonus Tip

If you’re a PHP Programmer, the official PHP documentation should be your bible. I would recommend going through the different sections and discovering what each function does. You’ll be amazed at just how much you can achieve with ready-made functions.

Hope you found this post helpful. Leave any comments below. Thanks!

Source webgeekly

5510656143_3b2c6a9f10_b

What’s The Difference Between CSS, HTML and PHP?

The-Difference-Between-CSS-HTML-and-PHP

Maybe you’re beginning to build a simple website, or just want a better understanding of the many acronyms you’ve been hearing lately.

CSS“, “HTML” and “PHP” are thrown around so often and with such ease, you’re embarrassed to ask what they mean.

Following is my attempt to explain these terms (mainly to myself) in plain English.

The Difference Between CSS, HTML and PHP

CSS = Style: Cascading Style Sheets (CSS) dictate your website’s look and feel.1

Font size, font color, font type, styling around images, page layout, mouse-over effects and more are all determined by CSS.

In WordPress, CSS can be edited within the “Editor” section under Appearance in the Dashboard. Some WordPress themes, like Headway, allow you to visually edit the CSS (meaning you don’t need to get eyeball headaches from coding).

The colors, fonts and styles of this entire website are driven by CSS.

HTML = Content: HyperText Markup Language (HTML) is the building-blocks of web pages.

HTML allows you to put images, text, videos, forms and other pieces of content together into a cohesive webpage. You can also tweak text words, resize images, and add links to either.

Anything that you can read or view on this website is being presented to you (by way of a browser) with HTML.1

PHP = Functionality: Originally meaning “Personal Home Page“, PHP is what makes your website do stuff(I really can’t say it any better than that).

It’s a language of web applications like WordPress plugins, Donation widgets and other things that do stuff.

If you use the search box at the top of the screen, PHP will perform the functions that need to be done to give you the search results.

Here’s another way to think about these technologies:


You can find a lot more information about these terms if you visit the links (made with HTML) throughout this post.

How would you explain these terms to a novice?

Original article has been published at Johnhaydon