Capable SEO

Inserts and Queries

Instructions on how to create some basic queries and inserts are here. At the completion of this tutorial you will be able create a page which will let people create usernames and passwords.

  1. First create a new .php file. You’ll need to create a basic form which posts to itself. The form needs to have 2 input text fields named “username” and “password” along with a submit button. The code for this is displayed below, I recommend just copying the info below and pasting it into your php file.
  2. Now that you have a form setup which will send information to you we get on to the php coding.
  3. Inside the code at the top of the page (above everything) create a section for your PHP code <?php ?>
  4. Your first step will be to receive the variables sent by the form, afterall if no variables are sent theres no reason to waste loading time. So add to the script a bit with the following. Form data is contained within a global variable labled $_POST. You can then access the
    individual fields by changing the name from “username” to whatever you wish.

    <?php
    $username
    =$_POST['username'];
    ?>


  5. Now we’ll need to test to see if there was any information in that variable. This code just performs a check, to see if what is inside the parenthesis () is true.
    If it is true then it will do something else (that something is contained within the { } tags. In the statement if ($username) we are saying if something happened to $username do the following.


    <?php
    if ($username)
    {

    }

    ?>

  6. Finally we’re on to the real query section. Here we will need to define the other variables of $password and $uid connect to the database. Check to see if any other users already have the chosen username. The insert the new username and password combination into the database. First lets connect to the database. Remember all of this code will be within the { } tags from the if statement in step 5.

    <?php
    if ($username)
    {
    /* you need to connect using the proper username and password if
    you installed the wamp server and didn't change any settings your
    username will be 'root' and your password wil be blank
    the below is a standard connect with password and username

    mysql_connect("localhost", 'yourusername', 'yourpassword')

    the below is what you can use if you still have the default wamp
    installation settings*/

    mysql_connect("localhost", 'root')
    or
    die(
    "could not connect");
    /* by adding the "or die" on to this you make the system report
    an error message. If theres a problem*/
    mysql_select_db("school");
    //Please choose the database name you created in the last tutorial;
    }
    ?>

  7. Ok now that you are connected to the database we should create the variables you’ll be using. First the password, this is basically a repeat of Step 4.

    <?php
    $password
    =$_POST['password'];
    ?>


  8. Now lets create the final variable the Unique ID. This will allow you keep track of data in an anonymouse way. In this step there are several functions including a random number creator, and a while loop.The random number creator will come first, this allows us to create a new ID for this user’s account.

    <?php
    /* the statement below will set $uid as a random number
    between 1 and 999,999. This gives us a 6 digit unique
    identification number.*/
    $uid=rand(1,999999);
    ?>

    Now we’ll run a check to see if there another ID equal to the newly generated one above. This is the first query.


    <?php

    /*query the table, this returns information
    regarding a row with the random id above.*/
    $query="SELECT * FROM users WHERE uid='$uid';";
    $result = mysql_query($query) or die(mysql_error());
    //place the results of the query into a variable
    $row = mysql_fetch_array($result);
    /*create a dummy variable with the value of username from the table.
    This will be blank if there aren't any users with the same id number.*/
    $dummy=$row['username'];
    ?>

    The following which is a loop which will means it will happen again and again as long as the requirements are met.

    <?php

    //while the $dummy != (is not equal) to "" (nothing) do what is inside the {}
    while ($dummy!="")
    {
    //first make dummy equal to nothing
    $dummy="";
    //set the uid to a new random number
    $uid=rand(1,999999);
    //query the database
    $query="SELECT * FROM users WHERE uid='$uid';";
    $result = mysql_query($query) or die(mysql_error());
    $row = mysql_fetch_array($result);
    /*set dummy as equal to the username, if the uid was
    unique then the username will now be equal to ""*/
    $dummy=$row['username'];
    }
    //finish the loop with a }
    ?>

  9. Now we’ll check to make sure the username isn’t already in the database and then either show an error message or insert the new user/password into the database.

    <?php

    /*query the database, similar to the first part of step 5,
    however instead of uid, we're looking at username*/
    $query="SELECT * FROM users WHERE username='$username';";
    $result = mysql_query($query) or die(mysql_error());
    $row = mysql_fetch_array($result);
    /*set dummy as equal to the uid, if the username was
    unique then the uid will now be equal to ""*/
    $dummy=$row['uid'];

    //if the username alraedy has information in it then display an error mesage
    if ($dummy!="")
    {
    echo
    "Sorry $username is already registered, please choose another username";
    /*notice I used $ in front of username. This will make the
    variable appear in the error message*/
    }

    /*or else do this (so if the if statement above isn't true insert a
    new row into the database.*/
    else
    {
    $query="INSERT INTO `users` ( `username` , `password` , `uid` )
    VALUES ('$username', '$password', '$uid');"
    ;
    $result = mysql_query($query) or die(mysql_error());
    echo
    "username: $username, password: $password created sucessfully";
    // the echo gives a success message which details the username and password.
    }

    ?>

PHP Posts and Redirects

Now we’re going to add in some functionality to your php. We’ll make a form which checks a person’s age then either redirects them to a different page, or displays an error message.

  1. First off is some html code for a form, the form will send via post method one variable for age.
    <form method=”post”>Age <input name=”age” type=”text” id=”age”></form>
  2. So now you’ve got a basic form that has a field for age. Now lets put in some a php code area and get started <?php ?>
  3. Now we need to put a variable there to catch whatever is posted back to the document. You can assign a vairable to a post like in the example.
    <?php
    /*$_POST is the method for describing a posted variable, then you describe the id of
    the variable within the [' '] tags.*/
    $age=$_POST['age'];
    echo
    "Age: $age";
    ?>

    This should print out Age: if you just start the page, and if you submit an age it will say Age: [your age here].

  4. Now lets add in a simple if statement determining if the age is below a certain point, if it is say below 13 we’ll assign a variable $error a sentence detailing how this site is made for those 13 or above.
    <?php
    $age
    =$_POST['age'];
    if (
    $age<13) {$error="Sorry this site is only for those aged 13 or above."}
    /* just having the variable in an if statement's ()s checks to see if the
    variable has been assigned anything or not. If it has it will run the statement.*/
    if ($error) {echo $error;}
    ?>

    Depending on what you submit to the page this will either print nothing or it will print Sorry this site is only for those aged 13 or above.

  5. Lets add in an else statement so that if they are able to see the site it will tell them that the site is redirecting them there now.
    <?php
    $age
    =$_POST['age'];
    if (
    $age<13) {$error="Sorry this site is only for those aged 13 or above."}
    if (
    $error) {echo $error;}
    else { echo
    "Your old enough to view the site, redirecting you now.";}
    ?>

    This will either tell the person they’re too young or tell them they’re old enough and the site is redirecting.

  6. The final part of the script is actually redirecting a person if they are of the correct age. So add in the following code to the redirect. header(’Location: http://www.example.com/’);
    <?php
    $age
    =$_POST['age'];
    if (
    $age<13) {$error="Sorry this site is only for those aged 13 or above."}
    if (
    $error) {echo $error;}
    else { echo
    "Your old enough to view the site, redirecting you now.";
    //remember you would be changing example.com below to whatever url you need.
    header('Location: http://www.example.com/');}
    ?>

    This will either tell you that your not old enough or redirect you to http://www.example.com, This lesson is now over.

How to do PHP While Loops

Now that you know how to use if then statements lets move on to a basic loop.

  1. Lets get started by opening your favorite editor and starting a fresh source page. Start off with the basic coding which denotes a php area. <?php ?>
  2. Now lets add in a variable and an echo statement. Give one variable a value of 0 then echo it.
    <?php
    $x
    =0;
    echo
    $x;
    ?>

    This should print out 0.

    PHP generally starts many constructs at 0, not at 1 so its generally better to start counting from 0 in programming..

  3. Now lets add in a basic loop. The while statement is very similar to an if statement except a while loop will do the things as long as its conditions are met (or until timeout which is generally 3-5 minutes depending on your server settings).
    <?php
    while (/*requirements*/)
    {
    //Stuff to do
    }
    ?>

    This won’t print anything yet

  4. Now lets make that actually do something. We’ll have it run 5 times, so while $x<5 do something. Of course we have to increase $x inside the loop otherwise it won’t end. So the only action we have right now is adding one to $x, we can do this with $x=$x+1; or in english x is equal to x +1.
    <?php
    $x
    =0;
    while (
    $x<5)
    {
    $x=$x+1;
    }
    ?>

    This won’t print anything yet

  5. Now lets add on an echo so we can see the progress of $x counting up towards 5.
    <?php
    $x
    =0;
    while (
    $x<5)
    {
    echo
    $x;
    $x=$x+1;
    }
    ?>

    This should print out “12345

  6. Ok now there is a better way to add one to $x and thats a special operation which is coded like this ++$x;
  7. Now lets add some text to each echo so it looks a bit nicer. You can print a variable and letters by using an echo with quotes. so in this statement echo “x: $x”; the first x will simply be the letter x and the second one which is preceded by a $ will be the variable.
    <?php
    $x
    =0;
    while (
    $x<5)
    {
    echo
    "x=$x";
    ++
    $x;
    }
    ?>

    This should print out “x: 1x: 2x: 3x: 4x: 5
    Now this doesn’t look much nicer (actually it looks worse!), but we’ll fix that in the next step.

  8. A PHP echo will place code directly into the html of a file. So if you type html code into the echo you can use different html functions to change displays. In this way you can make things bold, manipulate css styles etc. For now we’ll just add a <br> to the end of each line this will make the numbers go to different lines.
    <?php
    $x
    =0;
    while (
    $x<5)
    {
    echo
    "x=$x<br>";
    ++
    $x;
    }
    ?>

    This should print out:
    x: 1
    x: 2
    x: 3
    x: 4
    x: 5

If Then Math PHP Statements

  1. Lets get started by opening your favorite editor and starting a fresh source page. Start off with the basic coding which denotes a php area. <?php ?>
  2. Now lets add in some basic variables and an echo statement. Give two variables a value of 2, and a third variable a value equal to the previous to variables added together.
    <?php
    $x
    =2;
    $y=2;
    $number=$x+$y;
    echo
    $number;
    ?>

    This should print out 4 .

  3. Try changing the + to different mathmatical operators these are:
    / Divide
    * Multiply
    - Subtract
  4. Now we’re going to add in an if then statement. Basically if statements are logical, if certain requirements are met then do something. An if then statement looks like this
    <?php
    if (/*requirements*/)
    {
    //Stuff to do
    }
    ?>

    The if statement is one of the few that doesn’t require a ; after it.

  5. Now lets a simple statement that says, ‘if’ ‘$number is not equal to four’ ‘echo Thats not Four’. This code looks like this.
    <?php
    $x
    =1;
    $y=2;
    $number=$x+$y;

    if ($number!=4)
    {
    echo
    "Thats not Four";
    }
    ?>

    This should print out “Thats not Four

    The comparison operators in PHP are as follows:
    != Is not equal to
    == Equal to
    > Greater than
    < Less than
    >= Greater than or Equal to
    <= Greater than or Equal to

  6. Now lets say you want to check if the number is between 5 and 10. You’ll need to use two checks in the if instead of one. So you need to say ‘if’ ‘$number is greater than or equal to 5 and less than or equal to 10′ ‘echo number is between 5 and 10′. The code for this looks like this:
    <?php
    $x
    =1;
    $y=2;
    $number=$x+$y;

    if ($number>=5 && $number<=10)
    {
    echo
    "number is between 5 and 10";
    }
    ?>

    This shouldn’t print anything

    Logical Operators for PHP
    && and
    || or

  7. Now this is fine and all except what, happens when your number doesn’t fit the criteria? Nothing happens. So lets add on the final part of an If Then statement. So now PHP will go if $number is between 5-10 do this, or else do this. The code looks like this:
    <?php
    $x
    =1;
    $y=2;
    $number=$x+$y;

    if ($number>=5 && $number<=10)
    {
    echo
    "number is between 5 and 10";
    }
    else
    {
    echo
    "number is less then 5 or greater than 10";
    }
    ?>

    This should print number is less then 5 or greater than 10

Hello World

A small step for PHP (Hypertext Preprocessor) everywhere is just a simple “Hello World”. So we’ll out line a few basic commands here.

  1. Make sure you have a PHP enabled server on your computer. My preference is Wamp Server it installs a complete package with the latest PHP, MySQL tools and systems.
  2. Use your favorite processor to start a .php file. If you aren’t sure which allows you to do this, simply use notepad. If you use notepad when you save the file, choose all files from the list, then make your filename end in .php You should make sure that you save the .php file to your PHP testing server, generally on your local computer this folder will be called WWW.
  3. Second you need to tell the internet browser that your starting a section that will have PHP code inside of it. so you should use the basic identifiers to incase the code.

    <?php          ?>

    Everything contained within the <?php and ?> will be considered PHP code. All functions inside will be processed before the website loads. For this reason if there is an error in the PHP code, the entire website will likely not work, and either show an error, or a blank page. For this reason its important to test all PHP pages before launching them.

  4. Now we’ll move on and create a new variable. Think algebra, ‘X=4‘ etc. In PHP all variables have always have a $ sign. Therefore it would be ‘$X=4‘. Finally you have to add one more thing to make this a complete variable declaration (actually making $X equal 4). You need to add a colon ; after. This lets PHP know that your done with your command. The complete code looks like this.
    <?php

    $X=4;

    ?>

    So now X is equal to 4. Of course the object of this lesson is to write “Hello World” so instead of making $X equal to 4 lets make it equal to “Hello World”.

    <?php

    $X=”Hello World”;

    ?>

    Quite easy to change isn’t it. PHP is unique in that it defines variables based on what you put place in it. This makes it much easier then many programs since you don’t often have to worry about what types of variables are.

  5. We’re nearing the finish of our short tutorial. Now you need to actually place the words “Hello World” onto the screen. This is done by using the ‘echo’ function. The code works like this ‘echo‘ ‘$variable‘ ‘;‘ this allows you to place whatever is in the variable onto the screen. So lets place that into our code from above and make the program work.
    <?php

    $X=”Hello World”;

    echo $X;

    ?>

  6. Now you need to make sure you saved this to a place on your PHP enabled server. Go to it with your favorite web browser and you should see the words “Hello World“. Feel free to change the words around and experiment with it.
  7. Common errors:
    • Forgetting to place a ; after a statement.
    • Capitalization can cause no end of problems. PHP is a case sensitive programming language, which means that you could have two variables, $X and $x and they could be two completely different things! You also need to call the functions by their correct name, for example if you said Echo instead of echo the above function wouldn’t have worked.

This is the end of the first PHP Tutorial

Capable SEO