PHP Navigation using Switch

By: Jacob Manser (lefteh) Posted: 27-Dec-05, 22:38:01 Rated: General/Experienced

Alert!: Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

In this tutorial, you will learn how to use PHP’s “switch” capability to create your site’s navigation. The switch is basically an alternative to a million ifs or elseifs.

First of all, decide what GET variable your navigation will be based upon. For example, this tutorial will use $_GET[‘page’]. Therefore, our links will be like this: <a href=”?page=about”>.

Now, let’s learn the basic outline of a switch.


<?php
switch ($var) {

case “page1”:

break;

case “page2”:

break;

case “page3”:

break;

default:

break;

}

?>

Every time the “case” statement is used, the code is testing the value of the variable that is the argument of switch().

For example, in the above example it says “switch($var)”.
This means that the variable that will be tested is $var.
When it says case “page1”, it is seeing if the value of $var is “page1”. If it is, then it executes the code between the colon ( : ) and the break; statement.

The default: part acts like a last resort, like an else.

Now, let’s put this to use. Let’s say I have four pages on my site: Home, About, Products, and Contact. I will use $_GET[‘page’] as my switch variable, and make the links as follows:


<a href=”?”>Home</a>
<a href=”?page=about”>About</a>
<a href=”?page=products”>Products</a>
<a href=”?page=contact”>Contact</a>

The PHP code will be as follows:


<?php
switch($_GET[‘page’]) {

case “about”:
echo “About”;
break;

case “products”:
echo “Products”;
break;

case “contact”:
echo “Contact”;
break;

default:
echo “Home”;
break;

}

?>

 

Create an easy PHP Navigation with Query Strings

This system of doing things is pretty simple. First lets go over the breakdown of what exactly this script will do. Basically it will create an easy way to navigate your site that looks quite neat. EX. http://www.watever.com/index.php?id=tutorials. In the example the page being shown will be the tutorials page. Lets take a look at the code first, then we can run through a quick breakdown.

<?php
$id = $_GET[“id”];
$id = addslashes(strip_tags($id));

switch( $id )
{
default:
include ‘home.php’;
break;

case ‘home’ :
include ‘home.php’;
break;
}
?>

Some people use IF statements, but this way seems a little neater.

Line 1: Initiates the PHP file. Nothing really happens here.
Line 2: This is the opening of the switch statement. Basically it “GET”s the id from the address.
Line 4-6: Is the default switch statement. If there is no id then it will include the file home.php
Line 8-10: Is the first case. It says, IF the id is home THEN include home.php.

To add more links you just need to add more of the following:

case ‘contact’ :
include ‘contact.php’;
break;

Don’t forget to change the case and the include file.

Implementing The Code
Implementing the code is pretty simple as well. Basically you build your main page, and where you want your main content to appear you put in this SWITCH statement. Then for each file, (EX. home.php) you only put the content. Hers a quick example of what a page would look like:

<?php
include’dbconnect.inc.php’;
?>
<html>
<head>
<title>Xangelo</title>
<link rel=”stylesheet” type=”text/css” href=”style.css”>
</head>
<body>
<div class=”header”>
Navigation
</div>
<a href=”index.php?id=home”>Home</a>
<div class=”content”>
<?php include’id.php’; ?>
</div>
</body>
</html>

And you home.php file would look like this:

Welcome to my site

The file id.php contains your switch statement. If you need more help implementing this, feel free to drop me an email.

*Edit*
Made page slightly more secure with use of addslashes/strip_tags code performed on variable.

And that’s all folks. You can add as many cases as you need, and do anything you want in the meat of the cases.

 

 

Writing Form Data to a MySQL Database using PHP

Alert!: Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

In this tutorial, we will make a form and then submit what is entered to a MySQL database, and learn how to carry values between pages.

Let’s make a skeleton:


<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>

</body>
</html>

Now, we need to make our form!
We will leave the action blank because it is the same as the page itself. The method is post.


<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
</body>
</html>

Ok, so we now have our form set up. Now we have to learn conditionals in PHP. This is where the real power of PHP comes into play. The basic conditional follows this format:


if ($variable == “string”) {
echo “foo”;
} else {
echo “bar”;
}

The above code tells PHP to find the value of $variable, and compare it to “string”. If the value of $variable is indeed “string”, then the script will do whatever is between the following brackets. In this case, it will print “foo”. Otherwise, it will print “bar”.

You can also stick something between the if and the else. This is an “elseif”.


if ($variable == “string”) {
echo “Foo”;
} elseif ($variable == “secondstring”) {
echo “foobar”;
} else {
echo “bar”;
}

The elseif works like a second resort. If $variable does not equal “string”, then it will see if the value of $variable is instead equal to “secondstring”. If it does, then it executes the code between the brackets. If it doesn’t, then it goes to the else. You can have an unlimited number of elseifs in a conditional.

Here are some basic things that you can use as tests in your conditionals (the code between the parentheses in the if() part):

FYI $var == “string” – This tests if the variable matches the string exactly
$var == 1 – This tests if the variable matches the number exactly
$var != “string” – This tests of the variable does NOT match the string
$var != 1 – This tests of the variable does NOT match the number
isset($var) – this tests if the variable exists and contains a value.
!isset($var) – This tests if the variable does NOT exist
$var – This tests if the variable is set to a “true” value (1 or true)
!$var – This tests if the variable is NOT set to a “true” value (1 or true)

In conditionals, you can end and recommence the PHP code between the brackets as you like. Example:


<?php
$foo = “potato”;

if (isset($foo)) {
?>
This variable exists.
<?php
} else {
?>
This variable does <i>not</i> exist.
<?php
}
?>

This would print “This variable exists.” because of the fact that $foo is set to “potato”. If we hadn’t set it at the beginning, then the script would print “This variable does not exist.”

Now, we will move on to $_POST global variables.
When a PHP script is the action of a form with a “post” method, the inputted data is set as $_POST variables.
For example, if this was our form:


<form action=”send.php” method=”post”>
<input type=”text” name=”cheese”><br>
<input type=”submit” name=”submit” value=”Submit”>
</form>

then send.php would automatically have TWO variables set.

These are:
$_POST[‘cheese’] and $_POST[‘submit’].

The $_POST global variable follows this format:
$_POST[‘inputname’]

When a submit button is clicked, its $_POST variable is automatically set. Remember how we test that with a conditional?
Let’s assume I entered “swiss” in the field named “cheese” and I clicked submit. We will make the action, send.php, test to see whether or not the form was submitted. Then, we will print what I entered in the cheese field.


<?php
if (isset($_POST[‘submit’])) {
echo $_POST[‘cheese’];
}
?>

Ok, so now we will put this to use in our main page.
We will use a !isset conditional to display the form only if it has not been submitted already.


<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
}
?>
</body>
</html>

So now the form is only displayed if it has not been submitted already.

We will now begin to learn the act of submitting our form data to our MySQL database.

Let’s start by setting our database host, username, password, and name as variables at the top.
I will be using the following as my database information:
Host: localhost
Username: lefteh
Password: 1234
Name: MyDB

We’ll set the variables before anything else, just for clarity’s sake.


<?php
$db_host = “localhost”;
$db_user = “lefteh”;
$db_pwd = “1234”;
$db_name = “MyDB”;
?>
<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
}
?>
</body>
</html>

Now, how to connect to a MySQL database:


mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);

This code connects to your database using the first three variables, and then it selects the database that is the name of your fourth variable.

Let’s add that to our page.


<?php
$db_host = “localhost”;
$db_user = “lefteh”;
$db_pwd = “1234”;
$db_name = “MyDB”;
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
?>
<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
}
?>
</body>
</html>

Now we have a page that is connected to our database and displays a form if the same has not yet been submitted.
But what if it has been submitted?

Here, we will add an “else” clause.


<?php
$db_host = “localhost”;
$db_user = “lefteh”;
$db_pwd = “1234”;
$db_name = “MyDB”;
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
?>
<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
} else {

}
?>
</body>
</html>

So now, we need to do two things:
1. Write the inputted data into the database
2. Display a success message

Writing data to a MySQL database in PHP is actually quite easy:


mysql_query(“INSERT INTO `tablename` (fieldOne, fieldTwo) VALUES (‘$varone’, ‘$vartwo’)”);

That’s all! Let’s implement it in our code. We will assume that our database table name is “colors” and the fields are named “name” and “favoriteColor”. Remember our $_POST variables? We’ll set those to basic variables for simplicity’s sake and use them as the input variables. Some versions of browsers, servers, and PHP automatically do this. Just to be on the safe side, we will manually do it.


<?php
$db_host = “localhost”;
$db_user = “lefteh”;
$db_pwd = “1234”;
$db_name = “MyDB”;
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
?>
<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
} else {
$name = $_POST[‘name’];
$color = $_POST[‘color’];
mysql_query(“INSERT INTO `colors` (name, favoriteColor) VALUES (‘$name’, ‘$color’)”);
}
?>
</body>
</html>

Good!

Now all we need to do is add a little success message:


<?php
$db_host = “localhost”;
$db_user = “lefteh”;
$db_pwd = “1234”;
$db_name = “MyDB”;
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
?>
<html>
<head>
<title>My first MySQL form submission</title>
</head>
<body>
<?php
if (!isset($_POST[‘submit’])) {
?>
<form action=”” method=”post”>
Name: <input type=”text” name=”name”><br>
Favorite Color: <input type=”text” name=”color”><br>
<input type=”submit” name=”submit” value=”Submit!”>
</form>
<?php
} else {
$name = $_POST[‘name’];
$color = $_POST[‘color’];
mysql_query(“INSERT INTO `colors` (name, favoriteColor) VALUES (‘$name’, ‘$color’)”);
echo “Success! Your favourite colour has been added!”;
}
?>
</body>
</html>

And that’s all there is to it!

Building and Installing MaxMind GeoIP

Attention: Cet article/tutorial est ‰gé de plus de 45 jours. Ainsi les informations qu’il contient peuvent être, maintenant, dépassé. Merci de lire toutes les informations qu’il contient pour vous assurez que cet article fonctionnera bien sur votre système

 

FYI Mac OS X 10.3.4 is required will all relevant updates installed
Developers’ Tools are, as always, required for this tutorial
A version of Apache 1.3.x with APXS enabled is also necessary. (several PHPmac tutorials available)
Apache 2 version of mod_geoip is available, however, the method of installing this is outside the scope of this tutorial.

Step 1: Installing MaxMind GeoIP API----------The first step of this tutorial is a fairly straight foward build of the GeoIP API. The source is available free under the GPL

(% Represents the command line prompt)

% curl -O http://www.maxmind.com/download/geoip/api/c/GeoIP-1.3.4.tar.gz
% gnutar -xzf GeoIP-1.3.4.tar.gz
% cd GeoIP-1.3.4
% ./configure
% make
% make check
% sudo make install

Step 2: Installing mod_geoip for Apache----------Downloading and untarring are the first steps

% curl -O http://www.maxmind.com/download/geoip/api/mod_geoip/mod_geoip_1.2.4.tar.gz
% gnutar -xzf mod_geoip_1.2.4.tar.gz
% cd mod_geoip_1.2.4

Building the actual module is once again fairly simple. This step requires that you have built Apache previously with APXS support

sudo apxs -cia -I/usr/local/include -L/usr/local/lib -lGeoIP mod_geoip.c

Once this has completed you need to add the following lines to the end of your Apache httpd.conf file.

<IfModule mod_geoip.c>
# If GeoIP is turned on, turn it on
GeoIPEnable On
</IfModule>

The paths to the conf file is usually /etc/httpd/httpd.conf. Explaining how to change your httpd.conf file is not within the scope of this tutorial.
Restart Apache:

sudo apachectl restart

Step 3: Using in your PHP web applications----------Probably the easiest part of the entire process is using this in everyday use. Basically, the module provides the country information, all the hard work is done by the module itself. To access the country information in PHP you can use the following script.

<?PHP
$country_code = apache_note(“GEOIP_COUNTRY_CODE”);
$country_name = apache_note(“GEOIP_COUNTRY_NAME”);
?>

That’s it – all done. You can now call on this in all your PHP scripts. This is very effective method of automatically selecting Download Mirrors, providing location specific content, etc. for your visitors.

A word of warning: this method of determining geographical location can sometimes yield incorrect results. For example, if a multinational company has recently expanded to a new country and has taken IP addresses with it. This happened to me and I kept getting British mirrors on some websites when I wanted Irish ones. The moral of the story is to use this to make an initial “guess” – but always provide your users with a way to manually switch countries.

I have also written a little script that plots the location that GeoIP gives to a map of the world. It also checks the IP against the RIPE IP whois, or ARIN for US IPs. You can download the source here Requires GD and GeoIP (obviously)!

If you have any problems don’t hesitate to contact the support team. Click Here. A login is required.

Enjoy,

Compile Turck MMCache with your PHP

Warning: This article/tutorial is more the 45 days old. As such the information contained within could be, by now, out of date. Please read all information to make sure that this article/tutorial will work with your current version of the Operating System

Pre-requisite: You already have Apache and PHP running on your OS X 10.3.3 (Please refer to my previous tutorial)

STEP 1

Download the source of Turck MMCache from:
http://turck-mmcache.sourceforge.net/

STEP2

decompress the source and go to the source path

STEP3

type the following: (assuming you have installed php under /usr/local)

shell> export PHP_PREFIX=”/usr/local” <- or your installed PHP path
shell> $PHP_PREFIX/bin/phpize
shell> ./configure –enable-mmcache=shared –with-php-config=$PHP_PREFIX/bin/php-config

(if configure results in error)

shell> aclocal

and retry STEP3

shell> make
shell> sudo make install

after ‘make install’ you will see something like :
Installing shared extensions: /usr/local/lib/php/extensions/no-debug-non-zts-20020429/

STEP4

add below to the bottom of your php.ini (/usr/local/lib/php.ini)

zend_extension=”/usr/local/lib/php/extensions/no-debug-non-zts-20020429/mmcache.so”
mmcache.shm_size=”16″
mmcache.cache_dir=”/tmp/mmcache”
mmcache.enable=”1″
mmcache.optimizer=”1″
mmcache.check_mtime=”1″
mmcache.debug=”0″
mmcache.filter=””
mmcache.shm_max=”0″
mmcache.shm_ttl=”0″
mmcache.shm_prune_period=”0″
mmcache.shm_only=”0″
mmcache.compress=”1″

Please refer to http://turck-mmcache.sourceforge.net/ for information about configuring the options of the Turck MMCache

STEP 5

make directory:

shell> mkdir /tmp/mmcache

 

STEP 6

Restart your apache server

shell> sudo apachectl restart

In your Turck MMCache source directory there should be a file named “mmcache.php”, copy that to your Sites directory:

shell> sudo cp /[turck_mmcache_path]/mmcache.php ~/Sites

Then you should be able to access online mmcache control panel at http://localhost/~[user]/mmcache.php

There are a lot of configuration that you can do with it, please refer to http://turck-mmcache.sourceforge.net/ for details