Register

If this is your first visit, please click the Sign Up now button to begin the process of creating your account so you can begin posting on our forums! The Sign Up process will only take up about a minute of two of your time.

Results 1 to 7 of 7
Like Tree2Likes
  • 5 Post By Danny[MLWA]

Thread: PHP - The Basics

  1. #1
    Senior Member Danny[MLWA]'s Avatar
    Join Date
    Jun 2009
    Location
    Goldsboro, North Carolina, USA
    Posts
    109
    Member #
    19147
    Liked
    5 times
    From what I've seen, many web designers and developers do not know that much about PHP or choose to use proprietary Server Side Scripting like ASP, however I hope to make it a little easier by sharing my knowledge about php. This is a simple tutorial designed to get one started in php, it is no technical manual, it is only designed to help people "grasp" the concept of php.

    Rules of Thumb
    Like html, in php when you open something, you have to close it, but really the only thing that is unlike html, is the fact lines have to be terminated with the semi colon.
    PHP Code:
    <?php 
    // Opened PHP
    $whatisthis 'this is a string defining $whatisthis which all totaled up, is a line'// And terminated with ;
    // Closing PHP
    ?>
    Variables and Strings
    This is the most important part of PHP, variables! Once you have this part down pat and in your head, the ball is officially in your court. A variable is like in algebra class, the x -- 1+x=y, where x is ? Well if you make x 1, then the outcome of y changes.. changing y also changes the outcome of x. Like in algebra, these variables must be defined. A valid variable starts with the dollar sign ($) and contains alpha-numeric characters, EXCEPT it cannot contain spaces and it CANNOT begin with a number.
    PHP Code:
    $a_123 "somevar"// Good variable
    $abcde "somevar"// Good variable
    $1_abc "somevar"// NO GO (can't begin with a number)
    $abc def "somevar"// NO GO (can't contain spaces)
    $a#ddf = "somevar"; // NO GO (can't contain special characters) 
    Now the "basic" built-in functions to get you going on some puliminary programing:
    echo() - This will print the string defined between the prenthisis.
    PHP Code:
    echo('My Name is Danny'); // Would show in a web-page, My name is Danny.
    $name = ('Danny');
    echo(
    "My name is $name"); // Would show in a web-page, My name is Danny. 
    As you saw above, a string is a line of code that usually defines a variable or constant.
    PHP Code:
    ("This " .  $is " a string"
    But of course, $is is not defined, but is just for demonstration purposes only.

    As you can see a string is broken like that to show strict translation of the variable, usually when there is text "hugging" the variable or the string is set to flexible (for lack of words) interpretation (by using "s instead of 's) where strict interpretation is extremely literal by using the single quote.
    PHP Code:
    $strict "flexible"
    $string = ("This is a $strict interpretation."); // $string is, This is a flexible interpretation.
    $string = ('This is a $strict interpretation.'); // $string is, This is a $strict interpretation. 
    You can force adding strings and variables together by breaking the string and adding the period in-between to adjoin them as such:
    PHP Code:
    $string = ('This is a '$strict ' interpretation'); // $string is, This is a flexable interpretation. 
    Even though its strict, you broke the string and ajoined the variable from within. This is very useful for tricky strings like:
    PHP Code:
    $age 4;
    $string = ("My age=$age"); // $string is, My age=$age 
    Because $age is "hugging" the = or anything other than a space, it is not interpreted as a variable unless the string is broken like so:
    PHP Code:
    $age 4;
    $string = ("My age=" $age); // $string is, My age=4 
    Now lets talk about the basic "SUPER GLOBAL" variables; these are usually variables built into PHP or variables translated by the string proceeding the file in the URL after the ?... For instance, yourfile.php? -- After the ? you can start tacking on variables to inject into PHP separated by the ampersand (&), for example:
    yourfile.php?age=4&name=Danny&page=index
    You would call these in php as:
    PHP Code:
    $_REQUEST['thevariable'
    So the URL string I mentioned above could be echoed in the php file as such:
    PHP Code:
    echo("My name is $_REQUEST['name'] and I'm $_REQUEST['age'] years old.  You are viewing the $_REQUEST['page'] page."); 
    This would display:
    Code:
    My name is Danny and I'm 4 years old.  You are viewing the index page.
    Now in strings you can perform basic math... addition, subtraction, multiplication, and subtraction. These of course use the basic signs as well and are simply done in "reverse" from the math classes you've taken as such:
    PHP Code:
    $five 5;
    $six 6;
    $result $five+$six// $result is, 11 
    The wrong way:
    PHP Code:
    $five 5;
    $six 6;
    $five+$six $result// returns an error, result is undefined as you're declaring the sum of $five and $six as $result. 
    Now you have enough knowledge to build your own calculator!

    Create addition.php and edit it in your favorite text editor:
    PHP Code:
    <?php
    // My first php addition calculator!
    echo($_REQUEST['var1']+$_REQUEST['var2']);
    ?>
    Upload it to a web server and define after addition.php?var1=SOMENUMBER&var2=SOMEOTHERNUMBER

    Congratulations, this concludes part 1 of the tutorial! =)

    Conditional Statements
    Fun fun fun! Conditional if-elseif-else statements... Quite literally, that's what they are... These statements are telling php to do something if a condition is true, if not do something else...

    IF - If the statement is true....
    ELSEIF - Must DIRECTLY proceed the IF statement and provides an alternative match.
    ELSE - if the if statement and elseif statements are false, finish up with this.

    In these statements you have several operators at your disposal, but for explaination sake, we'll talk about a few...
    == - Is equal to
    != - Is not equal to
    <= - Is less than, or equal to
    >= - Is greater than, or equal to
    < - Is less than
    > - Is greater than

    Now you have conjunctions -- symbols you add between statements within the same statement:
    && - AND ex. (conditional && conditional)
    || - OR ex. (conditional || conditional)
    Lets give this a practical try...

    PHP Code:
    $name 'Danny';
    if(
    $name == 'Danny')
    {
    echo(
    'My name is Danny!');
    }
    elseif(
    $name == 'Tom')
    {
    echo(
    'My name Tom!');
    } else {
    echo(
    'My name is neither Danny or Tom!');

    Now if $name is "Danny" then the first statement would be true, and would print, My name is Danny!. If $name is "Tom" then the second statement would be true and would print, My name is Tom!. If you place anything else as $name, it would fault to the else statement of, My name is neither Danny or Tom!.

    Lets give that calculator a try again... This time, lets provide a few upgrades!

    create the file, calculator.php, and edit it with your favorite text editor...
    PHP Code:
    <?php
    // My second calulator program for PHP.

    // Lets start by determining whether we're going to be adding, subtracting, multiplying, or dividing...
    if($_REQUEST['calc'] == 'add')
    {
    // Addition calculator
    echo($_REQUEST['var1']+$_REQUEST['var2']);
    }
    elseif(
    $_REQUEST['calc'] == 'subtract')
    // Subtraction calculator
    echo($_REQUEST['var1']-$_REQUEST['var2']);
    }
    elseif(
    $_REQUEST['calc'] == 'multiply')
    // Multiplication calculator
    echo($_REQUEST['var1']*$_REQUEST['var2']);
    }
    elseif(
    $_REQUEST['calc'] == 'divide')
    // Division calculator
    echo($_REQUEST['var1']/$_REQUEST['var2']);
    } else {
    echo(
    "Woopsie, please define calculator.php?calc=...");
    }
    ?>
    Congratulations, this concludes part 2 of the tutorial!

    Functions and Loops
    Now for our last part, functions and loops, and definitely the most confusing or the most fun, however you wish to view it, but we'll start with the easy part.. Functions.

    A function is a pre-built set of instructions to be called when ever you please! You can inject variables directly into the function from the place of use. You "define" your function by first starting a line with the word function, and following it up with a space, the function name and the parenthesis with any variables you want injected within those parenthesis.
    PHP Code:
    function MyFirstFunction($yay)
    {
    // this is my first function and it does absolutely nothing, whatsoever... yet.

    Everything like with the conditionals between the brackets {} applies to this function and is included into it. You would call your function like it looks but without the "function" preceeding it.
    PHP Code:
    echo MyFirstFunction("nothinghere"); 
    This would inject into the function the variable $yay as, nothinghere. Lets complicate things a little, try and hang on...
    PHP Code:
    echo printName("Danny"); // returns, My name is Danny.
    function printName($name)
    // Danny was injected into the $name variable from the function call above.
    $return = ('My name is ' $name '.');
    return 
    $return;

    Now you should have functions down pat, they're really not that hard, though they can get complicated... Just remember that variables have to be defined within the function or injected.

    Before we jump right into a function you need to know the basics about arrays. Array is a gruesome sounding word, but it is quite simple. Imagine your operating system, in a folder you have files... an array is about the same thing... You have the array, and you have records in that array.

    $array = array('record1', 'record2', 'etc');

    You can "associate" the arrays with words instead of the default numbering system by declaring them in the array as such:
    $array = array('firstrecord' => 'record1', 'secondrecord' => 'record2); // and so on.

    You can also define arrays, "strait up" or forcefully...
    $array[0] = 'My name is Danny';
    $array[1] = 'My name is Tom';
    $array[2] = 'I have no name!';

    Now you know the basics of arrays, we can move right into loops!

    Loops are a little more complicated but we'll do the simplest loop now, you can learn other loops by looking them up on Google. The loop we're going to discuss is a for loop... there are 3 conditions to a for loop, 1) Initialization, 2) Condition, 3) Counter.

    for(initialization; condition, counter) is the proper syntax.

    Lets try this loop with the array above...
    PHP Code:
    for($i=0;$i<count($array);$i++)
    {
    echo(
    $array[$i]);

    Now lets study this a second... Notice the $i is the number of that array above. So $i=0, this is where the numbering starts, and it will then keep looping until it reaches the last record in the $array. (you can make it count down by doing the opposite for($i=count($array);$i>=0;$i--) which will count down!)
    With the example above, you'll notice that $i starts at zero, so the first record will be $array[0] which is My name is Danny, and will then show the next record $array[1], and so on.

    That concludes this tutorial! I hope you've learned something interesting and if you've enjoyed the tutorial let me know! Maybe I'll start some php-mysql tutorials and really get knee-deep in creating some truly dynamic pages =).
    Lead Web Designer
    MLW & Associates, LLP.
    W3C Standards Complaint and SEO Friendly
    Admin of Vraul
    WordPress.org Developer

  2.  

  3. #2
    WDF Staff smoseley's Avatar
    Join Date
    Mar 2003
    Location
    Boston, MA
    Posts
    9,729
    Member #
    819
    Liked
    205 times
    Very nice write-up!

  4. #3
    Senior Member
    Join Date
    Jan 2010
    Location
    bangalore
    Posts
    189
    Member #
    20785
    Very beautifully explained and presented. Thanks for the same.

  5. #4
    Senior Member
    Join Date
    Dec 2008
    Posts
    483
    Member #
    17875
    Liked
    1 times
    Nice tutorial...the only criticism i have is the use of $_REQUEST.
    Very rarely should you use request.

    Use the proper super global: $_POST, $_GET, $_SESSION, $_COOKIE.

    That way you're SURE where your value is coming from.
    I know there's a processing order when using $_REQUEST, but i still feel safe knowing that if i use $_POST there is no chance the value isnt coming from a form...if you use $_REQUEST...who knows where the value is coming from (someone can probably circumvent the processing order somehow)... BUt other than that, great tutorial.

  6. #5
    Senior Member Ganners's Avatar
    Join Date
    Feb 2011
    Location
    United Kingdom
    Posts
    415
    Member #
    27007
    Liked
    92 times
    Very good! Some points:

    Code:
    $a#ddf = "somevar"; // NO GO (can't contain special characters)
    Above isn't completely true (though I'd advise to keep this convention), you can't have some special characters but there are even more than you can have.

    Code:
    $age = 4;
    $string = ("My age=$age"); // $string is, My age=$age
    In this instance, instead of concatenating outside, you could simply do:

    Code:
    $age = 4;
    $string = ("My age={$age}"); // $string is, My age=4
    It is recommended you wrap all variables in braces within double quotes.

    For users using php 5.4(.1 ?), you have a better way to define arrays which is how it is in many languages.

    Code:
    $array = ['firstrecord', 'secondrecord', 'thirdrecord'];
    Mark Gannaway Software Developer

    Recent Experiments
    - Backpropogation Neural Network language solving (http://ann.ganners.co.uk/)
    - Animated image to ASCII (http://google.ganners.co.uk/)
    - 3D Paper Characters (http://cybergame.ganners.co.uk/)
    - Anagram solving (http://roflol.co.uk/)

  7. #6
    Banned
    Join Date
    Dec 2013
    Posts
    45
    Member #
    37912
    Liked
    1 times
    Great!! Thanks for this great tutorial.

  8. #7
    Banned
    Join Date
    May 2015
    Posts
    24
    Member #
    49599
    Thank you for sharing these useful tips.


Remove Ads

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
All times are GMT -6. The time now is 10:15 PM.
Powered by vBulletin® Version 4.2.3
Copyright © 2019 vBulletin Solutions, Inc. All rights reserved.
vBulletin Skin By: PurevB.com