Thursday, December 27, 2012

Common MySql Field Data Types


MySql : Common Field Data Types:
By Stephon Unomon
Google +

 

CHAR() – Fixed length field between 0 and 255 characters that can store any type of data. The length of the field is set regardless of the size of the data placed into it.

DATE – Date in YYYY-MM-DD format.

INT – Whole numbers only.  The number of digits can also be specified in parentheses, but is not necessary.

TEXT – Variable length text-only field with a maximum length of 65535 characters.

TIME – Time in hh:mm:ss format.

VARCHAR() – Variable length field between 0 and 255 characters that can store any type of data.  Unlike the CHAR() type, the length of each VARCHAR() field is determined by the data placed into it.

 

So, knowing this, let’s decipher our code example from above.

 

<?php mysql_query(“

CREATE TABLE Employees

(open the query to the DB and make this table with Employees as the name)

 

(employee_id INT,

(make this field with employee_id as the name and allow only whole numbers)

 

first_name VARCHAR(50),

(make this field with first_name as the name, allow any input, and limit it to 50 characters in length)

 

last_name VARCHAR(50)”)

(make this field with last_name as the name, allow any input, and limit it to 50 characters in length)

?>

Once you get the basic concepts, data manipulation with MySQL is not difficult. Let’s dive in a little bit more to the way tables are laid out.
 
 
Save Time While Building PHP Applications
Check Out
The #1 PHP GUI Controls

MySQL Creating Tables - Lessons For Beginners


Create Tables with MYSQL_QUERY
By Stephon Unomon
Google +

 

Now that we’ve selected the database we want to use, we need to put some tables in the database in order to store data. Before that happens, though, you need to think about what kind of data is going in to your tables. I’ll get to why in a moment. Here’s a simple example of table creation with the mysql_query command:

 

<?php mysql_query(“

CREATE TABLE Employees

(employee_id INT,

first_name VARCHAR(50),

last_name VARCHAR(50)”)

?>

You’ll need to define the type of data that is going in to each table field...which is why you’ll need to put some thought into your database before you start creating tables.

 

On the next page lies some common types of data. Remember, if you try to put text (TEXT) into a field that is defined to take numbers (INT), you’re going to get errors! (It’s the square-peg-round-hole scenario!)
 
Do You Want To Get The Most Out Of PHP?
Check Out
The #1 PHP TOOLS

Tuesday, December 25, 2012

MySQL Data Base Select Command - PHP For Beginners (MySQL)


Putting The Data In The Base
By Stephon Unomon
Google +

 

OK! We’re connected to a MySQL database! Far out! Now what? We need to put data IN to the database and use it!

 

So, here’s how we do it.

 

 

 

First of all, you have to select the database with the mysql_select_db() command.

 

<?php

mysql_select_db("my_db") or die(mysql_error());

?>
 

Tuesday, December 18, 2012

MySQL How To : PHP For Beginners Lesson 13

MySql How To
By Stephon Unomon
Google +
Making the connection to MySQL...
 

 
Here we will go over MySql as a part of the Beginner PHP Course.  This important to know so I put together a Mysql How To

First off, we need to be able to tell PHP to connect to a database before we can use it. The command is straight forward - mysql_connect().

 

<?php

$dbhost = "localhost"; // the db’s server

$dbname = "mysite_dbname"; // the db’s name

$dbuser = "mysite_dbuser"; // the db’s username

$dbpass = "password"; // the password for the user

mysql_connect ($dbhost, $dbuser, $dbpass) or die (mysql_error()); //connect to db or show error if failure

echo "Connected to database";

?>

Looking at the above code, everything is pretty self explanatory...except the “or die” thing. This is a method of handling errors. If for some reason PHP cannot connect to the database, the “or die(mysql_error())” part tells PHP to show us exactly what the error was. Most of the time it is human error - the wrong username, password, etc. was entered in the code. Check your work!
 
Hope You Enjoyed This Mysql How To
 

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:

 

Section 2 Overview - PHP For Beginners - Section 2 Wrap Up


Section Two Overview
By Stephon Unomon
Google +

 

In this section, we covered some more advanced features of PHP. Not for the timid, but not impossible to grasp!

 

IF - Do something if something is true.

ELSE - Do something else if it isn’t

ELSEIF - Add more choices to IF

SWITCH - Use this if you have a lot of ElseIf’s

ARRAY - One variable, many values

ASSOCIATIVE ARRAY - One variable, even more values

LOOPS - For, While, For Each - A way to repeat code

FUNCTIONS - Turn a big code chunk into a small one

SESSIONS - Carry unique data from page to page

COOKIES - Store session data on your viewer’s computer

FORM PROCESSING - Process web forms, such as a mailer

 

 

QUIZ TIME!

 

1. What are the 3 ways to comment code in PHP?

 

 

 

2. ELSEIF cannot be used without ____________

 

 

 

3. What are Cookies used for in PHP?
 
 
Check Out This Great

Thursday, December 13, 2012

Processing PHP Forms - PHP For Beginners Lesson 11

PROCESSING FORMS
By Stephon Unomon
Google +

KoolPHPSuite.Com
 

       What is one thing almost everyone wants to do with their website? Have a contact form. And, it isn’t as difficult as you’d think. We’re going to use the PHP mail() command to make one.

 

Make an HTML form with Name, Email and Message fields. Take the code below and place it in a PHP file to use as your action.

 

<?php

mail("myaccount@myisp.com", "Form Feedback", " // your address and subject

Name: $name

Email: $email

Message: $message

", "From: $email");

// Display results

echo("

<html>

Name: $name

Email: $email

Message: $message

</html>

");

?>
 
 
Stay Tuned For The Section 2 Overview & Quiz.....
And Of Course More PHP Lessons
 

Wednesday, December 12, 2012

Cookies Are Good - PHP For Beginners Lesson 10


Cookies (not just for your sweet tooth)
By Stephon Unomon
Google + 

 

You are hopefully familiar with Cookies - you get them almost anytime you visit a website. Cookies allow you to store information about your visitor’s session on their computer. 

 

One of the most common uses of cookies is to store usernames. That way when a viewer returns to your site, they don’t have to log in each time they visit.

 

You can create cookies in PHP with:

 

<?php

setcookie(name, value, expiration);

?>

There are 3 requirements when setting a cookie:

 

  Name:  This is where you set the name of your cookie so you can retrieve it later.

  Value:  The value you wish to store in your cookie.  Some common values are usernames or date last visited.

  Expiration:  When your cookie will be deleted from the user’s computer.  If you do not set an expiration date, the cookie will be deleted when the viewer closes their browser!

 

Getting information from a cookie is just about as easy as setting one. Remember the “ISSET” stuff a few minutes ago? PHP gets cookie data in a similar way, by creating an associative array (Yes, again!) to store your retrieved cookie data...using the $_COOKIE variable.

The array key is what you named the variable when it was set (so, obviously you can set any number of cookies!) So...

 

<?php

if(isset($_COOKIE['username'])){ // If there’s a cookie...

$username = $_COOKIE['username']; // set the variable...

echo "Welcome back, $username."; // and show the data in the cookie...

} else {

echo "No username was found. Sorry!";} // or show this if there wasn’t one.

?>

 

And, FYI...Cookies are stored as small text files on your computer (in case you did not know!)

 

Our next lesson will be...one of the most useful functions of PHP... find out tommorow!

PHP Tree View

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 Loops - Advanced PHP For Beginners Lesson 8

LOOPS
By Stephon Unomon

 

       We all have mundane, repetitive tasks we have to do. You know, like putting stamps on all those holiday greeting cards we send out every year? Well, from a programming angle, PHP can help us ease the workload on repetitive tasks in websites with a LOOP.

 

The first one we’ll discuss is the WHILE LOOP. It sounds like a weird carnival ride (I got sick on the While Loop - it was great!) but it is one of the most useful loop functions in PHP.

 

Logically, it looks like this:

 

while ( this conditional statement is true){

          //do this;

}

 

This isn’t real code - just an illustration of how it works. now, here’s what happens, step by step:

 

1. PHP checks the conditional statement. If it is true, move to step 2. If it is false, go to step 4.

2. PHP runs the code contained in the loop.

3. We go back to step 1 and start again, making a LOOP.

4. Once the conditional statement becomes false, the loop exits, and code placed after the loop runs.

 

Real World Usage for WHILE LOOPS

 

       The Creamy Bagel Company wants to show a pricing matrix on their website for up to a 20 bagel pack. But, since bagels are a valuable commodity, the price fluctuates regularly. You have to change it. You love your job.

 

Using a While Loop and some HTML, this can happen with relative ease, and you’ll only have to change one value when the bagel price changes (then charge for 3 hours of work!).

Read on...

 

<?php

$bagel_price = 2.15; //This is the price of one bagel

$counter = 1;

 

echo "<table border=\"1\" align=\"center\">"; //note the escapes for quotes!

echo "<tr><th>Quantity</th>";

echo "<th>Price</th></tr>";

while ( $counter <= 20 ) { //we just set the counter limit at 20

            echo "<tr><td>";

            echo $counter;

            echo "</td><td>";

            echo $bagel_price * $counter; //here we multiply

            echo "</td></tr>";

            $counter = $counter + 1; //here we add 1 to the counter and start again

}

echo "</table>";

?>

 

Our actual Loop code is highlighted in blue above. You’ll see that we set the variables $bagel_price and $counter. The $counter variable allows us to create a math function to increment the unit price by 1 each time we loop (see the $counter = $counter + 1 part at the bottom of the loop?)

So, while $counter equals less-than-or-equal-to 20, this loop will function. Once we hit 21, that’s it - no more loop!

 


Note on PHP Math functions
+  addition (You can use ++ to increment a value by 1)
-   subtraction
*   multiplication
/   division
 
 



 

Here’s what it looks like in a browser...and you can see at-a-glance what 13 bagels will cost you!

 

The FOR LOOP

 

       The FOR LOOP is very similar to a WHILE LOOP. The difference being a little bit more code is contained in the loop. The FOR LOOP can be a little more compact than a WHILE LOOP. Here’s the logic:

 

for ( create a counter; conditional statement; increment the counter){

            do this;

}

 

Let’s use our fluctuating bagel cost from above and write this out. Oops - bagels just went up 10 cents!

 

<?php

$bagel_price = 2.25;

 

echo "<table border=\"1\" align=\"center\">";

echo "<tr><th>Qu antity</th>";

echo "<th>Price</th></tr>";

for ( $counter = 1; $counter <= 20; $counter += 1) {

            echo "<tr><td>";

            echo $counter;

            echo "</td><td>";

            echo $bagel_price * $counter;

            echo "</td></tr>";

}

echo "</table>";

?>

 

Once again, the loop is highlighted in blue. You’ll notice that the counter is defined inside the loop as opposed to a variable outside.

 

And..to the right, you’ll see the output.

 

There’s one more Loop we’re going to cover, isn’t this exciting? Hello? Still there?

 

 

 

The FOR EACH Loop

 

       What if you want to loop through an Associative Array? (See? Told you we’d get back to this!) You can use FOR EACH to do this task. Where the WHILE and FOR loops run until an error is encountered, the FOR EACH loop will run through every element in the array.

 

Let’s revisit the associative array we set up with the trucks...

 

<?php

$truck[“Toyota”] = Tundra;

$truck[“Nissan”] = Titan;

$truck[“Dodge”] = Ram;

?>

 

To loop through the Makers / Models, we’d use this code:

 

<?php

forea ch( $truck as $make => $model){

            echo "Make: $make, Model: $model <br />";

}

?>

The code is written in a strange way, it isn’t obvious how it works. Let’s look at it in a simpler way:

 

$something as $key => $value

 

So, in english...



FOR each thing in the array, I want to refer to the key as $key and the value as $value. The operator ‘=>’ indicates the relationship between the key and the value...the key “points” to the value.

 

I think that’s about all we need to cover with Loops.


The Best GUI Controls 

PHP Arrays - PHP Arrays For Beginners Lesson 7

ARRAYS
By Stephon Unomon

 

          An Array can be thought of as a single variable that stores more than one value. An array uses a key to determine what value to reference. So;

 

$array[key] = value;

 

Key values start at “0” normally, as PHP likes to number things starting at Zero instead of One. It’s a programming thing, I don’t know either.

 

Let’s use our truck examples from above, and assign then in an array.

 

<?php

$truck_array[0] = "Toyota";

$truck_array[1] = "Dodge";

$truck_array[2] = "Chevy";

$truck_array[3] = "Ford";

?>

 

And here’s how we could output information from the array:

 

<?php

echo "Two great truck makers are "

. $truck_array[0] . " & " . $truck_array[1];

echo "<br />Two more great truck makers are "

. $truck_array[2] . " & " . $truck_array[3];

?>

 

Here’s is the output result of the above array:

 


 

 

 Associative Arrays

 

       An Associative Array is an array in which the keys are associated with values.

 

<?php

$truck[“Toyota”] = Tundra;

$truck[“Nissan”] = Titan;

$truck[“Dodge”] = Ram;

?>

 

A Syntax example using the Associative Array above:

 

echo "Toyota makes the " . $truck[“Toyota”] . "<br />";

echo "Nissan makes the " . $truck[“Nissan”] . "<br />";

echo "Dodge makes the " . $truck[“Dodge”];

 

And, when viewed in a browser...

 

You may not see the usefulness of the Array and Associative Array right now, but I think (hope) it will come together a little more once we hit the next lesson - LOOPS.

 
Kool PHP Suite

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.