Showing posts with label beginner php. Show all posts
Showing posts with label beginner php. Show all posts

Friday, December 14, 2012

PHP Database Function - PHP For Beginners Lesson 12


More Functionality with a database
By Stephon Unomon
Google +

 

       Nowadays you hardly ever hear PHP mentioned without MySQL close behind. Why? Well, PHP and MySQL make a great pair for web application development efforts. MySQL is often used in conjunction with PHP for the same reasons PHP is so popular - it is free, widely available, and most web hosts have it installed. There are other database systems that PHP works with, but MySQL seems to be the most common.

 

       In this section, I’ll familiarize you with using MySQL to connect to a MySQL database and perform the basics. Advanced MySQL and it’s SQL language is a little beyond the scope of this book, so we won’t dive very far in to heavy details (I don’t want to lose you!). However, MySQL’s commands are written in almost-plain-english, and you can usually figure it out just by looking at it.

 

       Most other PHP/MySQL books also tell you how to install MySQL and configure it. We’re not going to do that here. Your web host most likely has MySQL available for you, and they have simple ways to create databases. The two hosts that I have been using for years are pair Networks and Hostgator. Hostgator uses CPanel, and pair Networks uses a custom built control panel - both make it very easy to set up a database, and they provide the information you need to connect to it with.

 

So, let’s get connected!

With This:

 

Sunday, December 9, 2012

PHP Sessions - Advanced PHP For Beginners Lesson 9


PHP SESSIONS
By Stephon Unomon

 

       When your websites start to become more advanced and you find that you have a need for specific user data to be available throughout different pages on your website (think shopping cart!), it’s time for Sessions!

 

Starting a session is a snap.

 

<?php

session start();

?>

The webserver will attach a really really long random “session ID” to indicate a unique session. It looks something like: a8486dd2a3eacc136bd44ca653d8c5a2

 

A session isn’t worth a hill of beans unless we can store data in it. Fortunately, PHP can do this for us with an associative array, based on the $_SESSION variable. (Is some of this starting to come together?)

 

Let’s make a login form based on sessions!

 

<?php

session_start(); //  Starts a PHP session

echo "<form method=POST action=index.php>

  User Name: <input type=text name=\"username\">

  Password: <input type=text name=\"password\">

  <input type=submit>

  </form>";  // This is the HTML form

$_SESSION['username']=$_POST["username"]; // Enters the username into the array

$_SESSION['password']=$_POST["password"]; // Enters the password into the array

?>

 

Your username and password are now stored in an array that will last until the session is “un-set”.

 

Removing a session is done when either: The viewer closes their browser, or PHP runs the command to un-set a session, aka “destroy”.

 

You can think of it like this - your session is an Etch-a-Sketchtm that has information drawn on it. It’s there until you shake it!

 

<?php

session_destroy();

?>

Yes, it’s a tad violent...but gets the job done. This will clear out any data associated with the current session.

 

So, what if I want to remove specific data from a session without deleting the whole thing?

 

This can be done with an IF statement combined with  commands called “ISSET” and “UNSET”.

 

<?php

if(isset($_SESSION['items'])){ 

unset($_SESSION['items']);}

?>

 

So, logically...

 

If this specific key is set in this session, remove the key’s data.

The Best PHP Editor

Saturday, December 8, 2012

PHP IF Statement - Advanced PHP For Beginners Lesson 6

The IF statement
By Stephon Unomon

 

       The IF statement in PHP is very similar to using IF in real life. Like IF you don’t set your alarm clock, then you’ll be late to work in the morning. IF (and it’s friend ELSE) are known as “conditionals”.

 

       First off, let’s look at how PHP compares values for conditionals. You’ll see “operators” in any IF statement:

 

           ==        Equal to

           !=         Not equal to

           <          Less than

           >          Greater than

           <=        Less than or equal to

           >=        Greater than or equal to

 

So, a valid IF statement could be illustrated as follows:

 

<?php

if ($variable == "some value") {

echo "Correct";}

?>

Expanding on IF with ELSE

 

       You’ll most likely want to use IF with ELSE. ELSE gives you the option of doing something ELSE with your PHP script if IF doesn’t calculate one way or another. For example, you can have your site display something IF a condition is met (like a password was correct...see below!) or something ELSE if not. (Like a redirect if the password is not!)

 

 

 

 

Code example...

 

<?php

$five = “5”;

if ($five == “5”) {

    echo "You are correct";

} else {

    echo "You are incorrect";

}

?>

Real World Usage For If/Else

 

       You could create a simple password protected area using If/Else. A PHP page with a conditional statement could be set up to process an HTML login form. A variable “$password” could be set, and the Header command could be used to redirect on success or failure.

 

Your HTML page would be a simple form...

 

<form action="login.php" method="post">

<INPUT type="password" name="password">

<input type="submit">

</form>

 

This HTML form will set the variable in the “action” page (named login.php in this example) with the $_POST command (more on this later) and do one of two things: If the password is correct, it will show the desired content. If it is NOT correct, it will redirect to another URL (or page). Since the action is in PHP, viewing the source in the web browser isn’t going to reveal the password.

 

 

...And your PHP “Action” page would be an If/Else combined with a Redirect...

 

<?php

if($_POST['password'] == 'some_password'){

 

echo “

<!---Put your protected HTML content here...-->

“ ;

} else {

header ("location: some_error_page.html");

}

?>

 

...And Voila! A simple way to password protect a page. I wouldn’t use this for sensitive stuff (like putting your social security number online) but it’s good for a simple, single layer of security.

 

IF, meet ELSE. ELSE, meet ELSEIF

 

       The IF/ELSE statement is wonderful if you need to check for only one condition. But, what if you need to check for multiple conditions? Like, for instance, IF a truck is a Dodge, do this...ELSE a truck is a Chevy, do this...but what if you need to have options if a truck was a Ford?

In this example, we simply want to see if a truck is a Dodge or not. We can do this with IF / ELSE...

 

<php

$truck = "Chevy";

if($truck == "Dodge"){

          echo "It’s Ram Tough!";

} else {

          echo "We’ll Be There!";

}

?>

 

Now, if we wanted to see if the truck was a Ford, we’d add the ElseIf statement...

<php
$truck = "Chevy";
if($truck == "Dodge"){
          echo "It’s Ram Tough!";
} elseif {$truck == “Ford”}
          echo “Built Ford Tough!”;
} else {
          echo "We’ll Be There!";
}
?>
 
...And so on. You could continue to use ElseIf to declare other Trucks. One thing to remember about ElseIf is that it can’t be used without IF. So what if you have a lot of ElseIf’s?? Let’s see what’s behind the curtain, Bob...
 
Flip the SWITCH
 
       Sometimes we have to evaluate more than just a few cases, making ElseIf a tad cumbersome (do YOU want to write 20 ElseIf’s? I don’t!) Enter the more streamlined and efficient SWITCH command.Let’s add some more trucks to our list, shall we?
 
<?php
$truck = "Chevy";
echo "Drive a $truck, <br/>";
switch ($truck){
          case "Dodge":
                   echo "Ram Tough!";
                   break;        
          case "Ford":
                   echo "Built Ford Tough!";
                   break;        
          case "Toyota":
                   echo "Got The Guts?";
                   break;        
          case "Nissan":
                   echo "Shift_power";
                   break;        
          case "GMC":
                    echo "Professional Grade";
                   break;        
} ?>
That looks a little cleaner, don’t you think? A tad less clumsy that an equal number of If/Else statements. Make sure when you use Switch to include the “break” statement - it not, the information will be processed until the script “breaks” or ends.
 
Also, notice that there is no default statement for when we match our condition! We need to add something to Switch - the default case.
 
<?php
$truck = "Chevy";
echo "Drive a $truck, <br/>";
switch ($truck){
          case "Dodge":
                   echo "Ram Tough!";
                   break;        
          case "Ford":
                   echo "Built Ford Tough!";
                   break;        
          case "Toyota":
                   echo "Got The Guts?";
                   break;        
          case "Nissan":
                   echo "Shift_power";
                   break;        
          case "GMC":
                   echo "Professional Grade";
                   break;
          default:
                   echo "We’ll Be There!";
                   break;                  
} ?>
 
This way, if there are no matching cases, our default is displayed.
 
 




 

 

Introduction To Advanced PHP - Read Before Lesson 6

You Made It Past The Basics - Congratulations!
Please read over lessons 1-5 before starting this section.
By Stephon Unomon

 

       By now, you’ve got enough PHP knowledge under your belt to add basic PHP functionality in all of your websites. It’s pretty cool knowing things that a lot of others don’t know, and they’ll never be able to find out just by doing a “View Source” on your website (especially since you cant actually SEE PHP code by viewing the source in a browser!)

 

       In this section we are going to cover some more advanced PHP code. Things that you might not use just yet but once you are comfortable with PHP and want to get more out of it, you’ll be ready, my young apprentice.

 

       Quick tangent...before we get started here you are going to want to be able to place comments in your code. Why? It’s a heck of a lot easier to know why you wrote a specific line of code if you add comments...so you don’t come back in 3 months and ask yourself, “Was I drunk when I wrote this code??” Here are some examples of comment codes:

 

<?php

// This is a single comment line

# This is also a single comment line

/* This is a block comment, useful if you are working with a multi-line comment or are writing a story on your page that you don’t want people to see */

?>

You don’t have to use semicolons after each line, since the PHP server ignores comments because they aren’t actually commands. Now, on to more CODE! (ta-daaaa!)
 

PHP Lesson 1-5 Overview and Quiz

Section One Overview...
By Stephon Unomon

 

While we have not covered the entirety of basic PHP commands, the ones we have covered are among the most common and can be used in almost any web project.

 

ECHO: Outputs to the screen.

STRING: Content within a PHP command.

VARIABLES: Something equals something else.

DATE: A way to display date/time.

INCLUDE: Pull in the contents of another file.

REQUIRE: Require the contents of another file.

HEADER: Redirects to new file / URL.

 

 

And now....for a...

 

...QUICK QUIZ!!!

 

1. What is the difference between INCLUDE and REQUIRE?

 

 

 

 

2. Can we ECHO words with quotation marks? How?

 

 

 

 

3. What is a VARIABLE used for?


PHP UI Components

PHP Includes - PHP Lesson 4

PHP Includes
By Stephon Unomon

 

       A PHP include is used when you want to include the contents of one file inside another...a very useful command!

 

<?php

include("file.inc");

?>

Real World Usage for Includes

 

       Let’s say you are developing a 5 page website that you might be adding pages to. Your navigation HTML looks like this:

 

<html>

<head>

<title>My Navigation</title>

</head>

<body>



<a href=http://www.mysite.com/articles.php>Articles</a>


<a href=http://www.mysite.com/contact.php>Contact Us</a>

</body>

</html>

 

...and this is going to be in every page. Now, when you add a page to your website, you are going to have to change the code on all 5 pages to reflect the new link. This could take several minutes to do...and what if the site expands to 20 pages or more? It’s going to be a nightmare!

 

PHP Includes to the rescue!

Turn the page and watch PHP save our developer from certain doom!

 

       Let’s cut the menu link code out of the example above and paste it into a new plain text document (You can use Notepad on Windows or TextEdit on the Mac for this).

 


<a href=http://www.mysite.com/products.php>Products</a>



<a href=http://www.mysite.com/contact.php>Contact Us</a>

 

       Save this text file as navigation.inc. Paste the following in place of where the code was in the original HTML files...

 

<?php

include "navigation.inc" ;

?>

 

       Then save the HTML page as a PHP page. Voila! Any time you need to change the menu links, all you have to do is edit one file - the navigation.inc file!

 


A Note on Includes...
You don’t have to use .inc as the extension for an include - you can include almost any type of file with a PHP include - HTML, PHP, even other URL’s! One thing to keep in mind, however...is to strip out all the formatting code from the page you are including from (like the <html> and <body> tags). In other words, only include exactly what you need!
 

A Note on Includes...
You don’t have to use .inc as the extension for an include - you can include almost any type of file with a PHP include - HTML, PHP, even other URL’s! One thing to keep in mind, however...is to strip out all the formatting code from the page you are including from (like the <html> and <body> tags). In other words, only include exactly what you need!



 
 

 

I Require You To Include   

 

In PHP, you can also use the “Require” command in place of Include. The major difference between the two is that using Require will stop the script from running (the page won’t load completely) if it cannot find the page that is referenced for inclusion. An Include will allow the page to load, but it will just ignore the included code if it cannot be found.

 

 

 

 

Now let’s mesh it all together in an example!

 

       Imagine this...you are building a website. Your Greatest Undertaking Of A Website. 200 Pages. 400 Articles. Writing Code By Hand. The Titan Of Websites. You want to put advertising on each page (We’ll use GoogleTM AdSense as an example). You also want to test different color themes on the ad code, or change the ads periodically. You are also going to be quite generous and give copies of this website away for others to use.

 

       The questions start filling your mind...how can I easily change the ad colors or format? How can I let other people easily put in their AdSense publisher code?

 

We’ll use Variables and Includes to solve the problem!

 

Open up 2 blank text documents. The first one is going to be a settings file, the second one is going to be your Ad code.

 

In the settings file, you are going to want to set variables for things you know you are going to want to change, the main thing being the AdSense publisher code and the ad link colors. So, we’ll set the variables as below...

 

<?php

$ad_pub_num = “pub-0123456789”;

$eb_linkcolor = “006699”;

?>

The variable, $ad_pub_num, now reflects the AdSense publisher tracking code, and the link colors are the HTML color code 006699, which is a dark blue. Save this page as settings.php.

 

Now, grab your AdSense code snippet from Google...

 

<script type="text/javascript"><!--

google_ad_client = "pub-0123456789";

google_ad_width = 120;

google_ad_height = 600;

google_ad_format = "120x600_as";

google_ad_type = "text_image";

google_ad_channel = "1";

google_color_border = "FFFFFF";

google_color_bg = "FFFFFF";

google_color_link = "006699";

google_color_text = "006699";

google_color_url = "006699";

//--></script>

  <script type="text/javascript"


</script>

 

And paste it into the other open document...making some changes...

 

<?php echo "

  <script type=\"text/javascript\"><!--

google_ad_client = \"$ad_pub_num\";

google_ad_width = 120;

google_ad_height = 600;

google_ad_format = \"120x600_as\";

google_ad_type = \"text_image\";

google_ad_channel = \"1\";

google_color_border = \"FFFFFF\";

google_color_bg = \"FFFFFF\";

google_color_link = \"$eb_linkcolor\";

google_color_text = \"$eb_linkcolor\";

google_color_url = \"$eb_linkcolor\";

//--></script>

  <script type=\"text/javascript\"


</script>

?>

 

...and save this file as ads.php.

 

 

 

Do you recognize the changes we made? We’ve told PHP to echo the code to the screen, and put in the variables that we set in the settings.php file. Since we are doing an ECHO, we’re displaying the quotation marks in the output with the \” code (That’s the way the AdSense snippet works). Now we are ready to call these files from the main web pages!

 

At the beginning of your content pages, you will want to add this code:

 

<?php

require “settings.php”;

?>

This tells the page that it requires the contents of Settings.php file to be included. Including this code on each page sets the variables we will use throughout the site.

 

Now, call the ads in the places you want them:

 

<?php

include “ads.php”;

?>

This will pull in the code from the ads page we made, including the variables we set, and show those ads wherever you care to place them. So, your ad link colors will appear in a dark blue and the example publisher number - pub-0123456789 - will show up in the ads. Name each one of your content pages as .php instead of .html, and you’ll be good to go! If you decide you want to change colors of the ads (or change the AdSense publisher ID code), you only have to make that change in ONE file instead of 200 - the settings.php file!


PHP Components