Beginners PHP Tutorial – Arrays and Web Forms Part 3

November 3, 2008 by admin  
Filed under PHP

High Quality PHP Tutorial Videos – Taught by Experts
We also have extensive PHP Tutorials in high quality video format. These are ideal for beginners who need to master PHP quickly
Title / Free Demo :
Beginners PHP Tutorial Videos
Author:
Mike Morton
Duration:
6 Hours – Lessons: 86

PHP Arrays and HTML Forms – Part 3.

PHP Arrays and HTML Forms

This beginners PHP tutorial covers creating Arrays – Suitable for all versions of PHP

This is tutorial #3 in our Array Series. Today you’ll learn how to collect data from a web form and convert it into an array for further processing on the backend.

Why would you need to create an array from a web form? Good question and here is a good answer!

What would you like on that Pizza, sir?

Let’s look at a simple web form for a pizza shop that provides online ordering. We’ll skip over the parts of the form that collects name and address, etc., and go right for the meat (and cheese) of the problem.

The form above allows the user to select the pizza size from a drop-down containing the values Large, Medium, and Small. Nothing special going on there. We name that drop-down “size”, and use the built-in ‘option value’ field to add all of the sizes. In the code view, it would look like this:

<select name="select">
       <option>-- Select --</option>
        <option value="Large">Large</option>
        <option value="Medium">Medium</option>
        <option>Small</option>
 </select>

The real magic happens when we get to the add-on ingredients. Because we want the user to be able to select multiple ingredients, radio buttons were not an option. That’s because radio buttons use a simple off/on methodology. If you have multiple radio buttons in a group, radio buttons are not an option.

We could have used a multi-select drop-down list. That’s the type of drop-down where you can press and hold the Ctrl key while selecting multiple options, but that solution can be difficult for users to grasp. So, the checkbox is the right choice. It allows the user to select multiple options by simply click on each ingredient choice.

Normally, a checkbox looks like this when in code view:
<input type=”checkbox” name=”SomeName” value=”SomeValue” />

If you wanted to have multiple checkboxes to support our ingredients list, you could create them like this:

<input type=”checkbox” name=”Cheese” value=”xtracheese” />
<input type=”checkbox” name=”SomeName1″ value=”pepperoni” />
<input type=”checkbox” name=”SomeName2″ value=”sausage” />
<input type=”checkbox” name=”SomeName3″ value=”onions” />

But that wouldn’t be a very efficient way to do it. Why? Because you would have to write code on the backend using a lot of “if” statements to loop through each variable to see if it was checked. That’s not very efficient.

PHP Arrays to the rescue

By simply altering the way we name each checkbox slightly, we can have the HTML form create an array and pass it to our backend processing script.

<input type="checkbox" name="options[ ]" value="xtracheese" />
<input type="checkbox" name="options[ ]" value="pepperoni" />
<input type="checkbox" name="options[ ]" value="sausage" />
<input type="checkbox" name="options[ ]" value="onions" />

Do you see the difference between this example and the one above it? Look carefully.
Notice that all of the checkboxes have the same name value. They are all called ‘options’. Now, there is nothing special about the name. We could have called them all ‘ingredients’, or anything else for that matter. The real magic is the square brackets [ ] that we added after the name.

These brackets tell PHP that we are passing it an array and that multiple values may exist. If we had eliminated those brackets, and simply created four checkboxes all with the same name, PHP would only recognize the checked value of the first checkbox it processed. The additional ingredient choices would be lost.

Processing that pizza order

So now that you have that array of choices passed to your backend script, what do you do with them? You already now the answer. You simply process it using the foreach function that you already learned.

Depending upon whether your form uses the get or the post method, your array is in the $_POST or the $_GET array. Let’s assume $_POST for this example.

foreach($_POST[‘options’] as $ingredients) {

< add your own processing here>;

}

Lets give it a try, create a HTML page and paste the following code in between the <body> tags:

<form id="form1" name="form1" method="post" action="pizza-process.php">
<strong>Papa's Famous Pizza</strong>

<select name="size">
<option>-- Select --</option>
<option value="Large">Large</option>
<option value="Medium">Medium</option>
<option>Small</option>
</select>

What would you like on that Pizza, sir?

<input type="checkbox" name="options[ ]" value="xtracheese" />
Extra Cheese
<input type="checkbox" name="options[ ]" value="pepperoni" />
Pepperoni
<input type="checkbox" name="options[ ]" value="sausage" />
Sausage
<input type="checkbox" name="options[ ]" value="onions" />
Onions

<input type="submit" name="button" id="button" value="Order Your Pizza" />

</form>

Create a PHP page and call it pizza-process.php, paste the following code into the PHP file :

<?php
  echo "I would like a  $_POST[size] Pizza ";
// find what extras are required
  foreach($_POST[options] as $ingredients) {
echo"With $ingredients ";
} 

?>

Beginners Flash Tutorial – Working with MYSQL and PHP

October 30, 2008 by admin  
Filed under Flash Tutorials, PHP

High Quality – Flash Tutorial Videos – Taught by experts.
We also have extensive Adobe Flash Tutorials in high quality video format. These are ideal for beginners who need to master Flash quickly

Title / Free Demo : Adobe Flash CS3 Tutorial Videos
Author:
James Gonzalez
Duration:
11 Hours – Lessons: 125

Flash with PHP / MySQL

The code used in this tutorial is mainly ActionScript 2.0, with notes for using ActionScript 3.0 – basic knowledge of databases (particularly MySQL) and server-side scripting concepts is assumed, for users who require an a tutorial on Beginners PHP and MySQL we recomend the Beginners PHP Training Video

Given that Flash is used primarily on the Web, database driven components are a common requirement. In order to use data in this way within your Flash movies, you will need to use some sort of server-side scripting language, such as PHP. We use server-side scripting to communicate with a data source on the server, and Flash has some built-in capabilities for handling the data at the client-side.

To demonstrate, we will create a simple database-driven Flash movie using PHP and MySQL. This example will need to be deployed on a server with PHP and MySQL installed.

In MySQL, create a database called ‘flashtest’, with one table in it called ‘flashdata’; in the table create just one field (for simplicity – the details of the database are not important), name the field ‘flash_text’ and choose VARCHAR as the data type. Enter a few rows of data into the table, any strings of text will be fine.

Now we need PHP code to connect to and query your database. Create a file called get_data.php in the directory you intend to put your Flash file in – this will need to be on the same server as the MySQL database for the following code to work. In get_data.php enter the following code (replacing username and password with your own):

Select All

<?php

//connect to the local MySQL
mysql_connect("localhost", "username", "password");

//select your database
mysql_select_db("flashtest");

//query the database
$query="select * from flashdata";
$result=mysql_query($query);

//find out how many entries there are
$num=mysql_num_rows($result);

//write variable out - this is what the Flash document will retreive
echo "&num=".$num;

//keep count
$count=0;

//loop through and write the data into variables for the flash document
while($row=mysql_fetch_array($result))
{
   //write out each entry as a variable
    $entry=$row["flash_text"];
    echo "&t".$count."=".$entry;
    //increment the count variable
    $count++;
}

?>

Tip: you can test your PHP at this stage by fetching get_data.php in a Web browser – it should look something like this:
php test

Now to use the data within a Flash movie, create a new Flash document and save it on the server also. The Flash document is able to access the variables written out by your PHP script via the GET variable. Open the Actions panel for Layer 1 and enter the following code (replacing ‘filepath’ with the path to your PHP script):

Select All

      //load the variables into a MovieClip by calling the server-side script
var data_mc:MovieClip=_root.createEmptyMovieClip("data_mc", _root.getNextHighestDepth());
     //loadVariables parameters: url, movieclip, method
loadVariables("http://localhost/filepath/get_data.php", data_mc, "GET");

    //create the function for using the data
data_mc.onData=function()
{
    //get the total number of entries
    var numEntries:Number=data_mc.num;
      //loop through the entries
   for(var i:Number=0; i

Now test your movie, it should look something like this:
output

For Flash MX and above, you can alternatively use the LoadVars object with the following syntax:

Select All

//create LoadVars object
var lv:LoadVars=new LoadVars();
//load the data
lv.load("http://localhost/filepath/get_data.php");
//setup load function
lv.onLoad=function(success)
{
//get the data
var numEntries:Number=lv.num;
//otherwise syntax is the same as above
};

If you’re using ActionScript 3.0, the syntax will be slightly different; you need to use the URLRequest and URLLoader objects to load the data into Flash.

PHP Tutorials – Arrays Part 2

October 20, 2008 by admin  
Filed under PHP, Recent Tutorials

High Quality PHP Tutorial Videos – Taught by Experts
We also have extensive PHP Tutorials in high quality video format. These are ideal for beginners who need to master PHP quickly
Title / Free Demo :
Beginners PHP Tutorial Videos
Author:
Mike Morton
Duration:
6 Hours – Lessons: 86

Advanced PHP Arrays

This tutorial covers creating Arrays – Suitable for all versions of PHP

Don’t let the word advanced worry you. You are simply advancing along in your knowledge about how to use these amazing data structures.

Arrays are like tables in that they have columns and rows. And, thanks to the array functions PHP makes available, they can be manipulated like tables in many ways.

In the introduction to PHP Arrays tutorial , you learned about how to create indexed and associative arrays. I wrote that arrays were powerful tools, especially when combined with the foreach function and with the other functions designed especially for manipulating the data within arrays.

In this lesson, I’ll show you some practical uses for arrays and how to get them working their hardest for you.

Displaying All Elements in an Array

In the previous tutorial we created these two arrays:

$mystaff = array(0=>’Matthew’,
1=>’Mark’,
2=>’Luke’);

$salaries=array(“Matthew”=>65000,
“Mark”=>75000,
“Luke”=>100000);

Let’s create an array that lets us store the staff member’s name and salary together. Then we’ll use PHP’s foreach function to display them.

$mystaff[‘Matthew’]=65000;
$mystaff[‘Mark’]=75000;
$mystaff[‘Luke’]=100000;

This array structure may look odd, but all we have done is to create an associative array and use the name of each staff member as the key.

This is a great little trick that will play right into the hands of the foreach loop below. We’ll look at the syntax first and then I’ll explain the logic.

Foreach Syntax

foreach( $mystaff as $Name => $salary){
echo “Name: $Name, Salary: $ $salary “;
}

Name: Matthew, Salary: $65000
Name: Mark, Salary: $75000
Name: Luke, Salary: $10000

How It Works

The foreach statement above translates to this:

For each element of the $mystaff associative array I want to call the key by the name of $Name and the value that’s related to that key by the name $salary.

Then I want to print each of those values, one set at a time, until I reach the end of the array.

The foreach statement I provided uses the as modifier, and the as modifier uses the “=>” operator. Just think of this as a finger pointing from the key to the value.

Create a new PHP document and name it foreach.php. Copy the code below into the document and upload it to your web server and open the page in a browser.


Select All

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//
EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Arrays</title>
</head>
<body>
<?php   $mystaff[‘Matthew’]=65000;   $mystaff[‘Mark’]=75000;
$mystaff[‘Luke’]=100000;   foreach( $mystaff as $Name => $salary){
 echo "Name: $Name, Salary: $ $salary ";   }
echo 'I have '. count($mystaff). ' Staff members.';   ?>
</body>
</html>

PHP Array Functions

Here are examples of how PHP array-specific functions provide quick ways to enhance the power of arrays in your PHP programs.

Counting Array Elements

Count() returns the number of elements in an array. Use the Count() function to see how many staff members there are.

echo ‘I have ’. count($mystaff). ’ Staff members.’;

Sorting Array Elements

To sort the names alphabetically before displaying them, use the asort() function.

asort($mystaff);

Array Element Math

To calculate the total payroll for your staff, use the array_sum() function.

Echo ‘The total salary paid to my ‘ .count($mystaff). ’ Staff members =’ . array_sum($mystaff).’’;

Adding Array Elements

You could add a new employee quickly using the array_push() function.

array_push($mystaff[‘John’], 55000);

John would be added to the end of the array. Calling asort(), after array_push(), would alphabetize the array properly.

Deleting Array Elements

If John was hired to replace Matthew, the unset function would send Matthew to the unemployment line and asort() would restore the array’s sorted order.

unset($mystaff[‘Matthew’]);
asort($mystaff);

Tutorial Summary

These are just a few of the 75 functions PHP makes available for working with arrays. You can find the entire list, along with their syntax, by visiting PHP’s online Array Function Manual. If you would like to learn more about PHP and Arrays we offer a extremely comprehensive PHP video tutorial that offers indepth, step-by-step instructions.

PHP Tutorials – Arrays Part 1

October 20, 2008 by admin  
Filed under PHP, Recent Tutorials

High Quality PHP Tutorial Videos – Taught by Experts
We also have extensive PHP Tutorials in high quality video format. These are ideal for beginners who need to master PHP quickly
Title / Free Demo :
Beginners PHP Tutorial Videos
Author:
Mike Morton
Duration:
6 Hours – Lessons: 86

PHP Arrays – Basics

This tutorial covers creating Arrays – Suitable for all versions of PHP

Introduction to the PHP Array

The array data structure provides a convenient way to store multiple values in a single variable. An Array uses pointers or index keys to map each value stored within it. The type of pointer, and the syntax for accessing it, varies depending upon the array type used. An array is permitted to store other arrays as values. Here is a look at both of PHP’s array types and how they are created and used.

Indexed Array
An indexed array uses integers as the key. The Array index begins at 0. PHP imposes no limit on the maximum number of elements an array may contain, so there is no maximum ending integer. Of course, array size is subject to the memory limitations established in the PHP.ini file as well as of the server where PHP is running.

Associative Array

Associative arrays use string values as keys.

Creating an Indexed Array

An array can be created simply by storing a value to a variable that uses the array structure.

Example:


Select All

$mystaff[0]=’Matthew’;

The above method creates an indexed array. This method is often used when the array will be built with values that can not be pre-determined or that will be created on the fly.

If the values of the array are known ahead of time, you could use this syntax:

Example:


Select All

$mystaff = array(0=>’Matthew’, 1=>’Mark’, 2=>’Luke’);

In the above example, the array has 3 elements, even though the last element’s key is the integer 2. New PHP programmers may forget the indexed array key structure is zero-based, hence the 3rd element in the above example is referanced by 2 and not 3.

Both indexed array creation methods are interchangeable. You do not have to use one method under any particular circumstance.

Displaying an Indexed Array

The value of an indexed array element is displayed by referencing the array element by its key.

Example:

Select All

echo "The names of my three staff members are:
$mystaff[0] . ", " . $mystaff[1] . ", " . $mystaff[2];

Give it a try, create a new document enter the following code


Select All

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//
EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
<title>Arrays</title>
</head>
<body>
<?php   $mystaff = array(0=>’Matthew’,   1=>’Mark’,   2=>’Luke’);
 <p>echo "The names of my three staff members are: ".   $mystaff[0] . ",
" . $mystaff[1] . ", " . $mystaff[2]; ?>
</body> </html>

>and save it as array-test.php, upload it to your web server and view it.

Creating an Associative Array

An associative array uses a string value as the key. Where an indexed array is typically used to store strings, an associative array is typically used to store numeric values. However, it is entirely up to you which array type you use. These are guidelines, not rules.

In this example below, we will create an associative array containing salary information for those three staff members we created in the indexed array example above.

Example

$salaries["Matthew"] = 65000;
$salaries["Mark"] = 75000;
$salaries["Luke"] = 100000;

Instead of declaring each array value on its own line, you could also use this syntax:


Select All

$salaries=array("Matthew"=>65000, "Mark"=>75000, "Luke"=>100000);

Displaying an Associative Array

Select All

echo "Matthew’s salary is: $" . $salaries["Matthew"] . "". "Mark’s salary is:
$" . $salaries["Mark"] . "".
"Luke’s salary is: $" . $salaries["Luke"];

Give it a try, delete the contents of your array-test.php page and replace it with the follow:

Select All

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//
EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
<title>Arrays</title>
</head>
<body>
<?php   $salaries=array("Matthew"=>65000,   "Mark"=>75000,
"Luke"=>100000); echo "Matthew’s salary is: $" . $salaries["Matthew"] . "".
 "Mark’s salary is: $" . $salaries["Mark"] . "".
  "Luke’s salary is: $" . $salaries["Luke"]; ?>
</body>   </html>

After saving your page, upload to your webserver and view. You know have a fundamental knowledge of creating and displaying Arrays in PHP.

Summary

Arrays are powerful tools, especially when used with the for and while functions. There are other PHP functions designed especially for working with arrays. They provide convenient methods for sorting, transversing, and manipulating arrays. We’ll look at these in next PHP Array tutorial.