Archive

Archive for October, 2009

Java Script Tutorials

October 23, 2009 Leave a comment

Welcome To
JavaScript for the Total Non-Programmer

This tutorial will take you step by step through the fundamentals of Javascript. You will learn how to write functions, use data from text boxes, create IF-THEN conditionals, program loops, and generally make your web page “smarter.”

I teach computer classes for a living to corporate clients of all levels. After 2 years of teaching, I have learned a lot about communication between people of various levels of computer experience. This tutorial assumes that you have no prior programming experience, but that you have created your own HTML pages.

If you find this tutorial helpful, please let me know (it’s my only reward). Also, links are graciously accepted.

What is JavaScript?

Javascript is an easy-to-use programming language that can be embedded in the header of your web pages. It can enhance the dynamics and interactive features of your page by allowing you to perform calculations, check forms, write interactive games, add special effects, customize graphics selections, create security passwords and more.

What’s the difference between JavaScript and Java?

Actually, the 2 languages have almost nothing in common except for the name. Although Java is technically an interpreted programming language, it is coded in a similar fashion to C++, with separate header and class files, compiled together prior to execution. It is powerful enough to write major applications and insert them in a web page as a special object called an “applet.” Java has been generating a lot of excitment because of its unique ability to run the same program on IBM, Mac, and Unix computers. Java is not considered an easy-to-use language for non-programmers.

Javascript is much simpler to use than Java. With Javascript, if I want check a form for errors, I just type an if-then statement at the top of my page. No compiling, no applets, just a simple sequence.

What is Object Oriented Programming?

Everyone that wants to program JavaScript should at least try reading the following section. If you have trouble understanding it, don’t worry. The best way to learn JavaScript is from the examples presented in this tutorial. After you have been through the lessons, come back to this page and read it again.

OOP is a programming technique (note: not a language structure – you don’t even need an object-oriented language to program in an object-oriented fashion) designed to simplify complicated programming concepts. In essence, object-oriented programming revolves around the idea of user- and system-defined chunks of data, and controlled means of accessing and modifying those chunks.

Object-oriented programming consists of Objects, Methods and Properties. An object is basically a black box which stores some information. It may have a way for you to read that information and a way for you to write to, or change, that information. It may also have other less obvious ways of interacting with the information.

Some of the information in the object may actually be directly accessible; other information may require you to use a method to access it – perhaps because the way the information is stored internally is of no use to you, or because only certain things can be written into that information space and the object needs to check that you’re not going outside those limits.

The directly accessible bits of information in the object are its properties. The difference between data accessed via properties and data accessed via methods is that with properties, you see exactly what you’re doing to the object; with methods, unless you created the object yourself, you just see the effects of what you’re doing.

Other Javascript pages you read will probably refer frequently to objects, events, methods, and properties. This tutorial will teach by example, without focusing too heavily on OOP vocabulary. However, you will need a basic understanding of these terms to use other JavaScript references.

Objects and Properties

Your web page document is an object. Any table, form, button, image, or link on your page is also an object. Each object has certain properties (information about the object). For example, the background color of your document is written document.bgcolor. You would change the color of your page to red by writing the line: document.bgcolor=”red”

The contents (or value) of a textbox named “password” in a form named “entryform” is document.entryform.password.value.

Methods

Most objects have a certain collection of things that they can do. Different objects can do different things, just as a door can open and close, while a light can turn on and off. A new document is opened with the method document.open() You can write “Hello World” into a document by typing document.write(“Hello World”) . open() and write() are both methods of the object: document.

Events
Events are how we trigger our functions to run. The easiest example is a button, whose definition includes the words onClick=”run_my_function()”. The onClick event, as its name implies, will run the function when the user clicks on the button. Other events include OnMouseOver, OnMouseOut, OnFocus, OnBlur, OnLoad, and OnUnload.

Chapter 1, The Message Box

This is a very simple script. It opens up an alert message box which displays whatever is typed in the form box below.

Type something in the box. Then click “Show Me”


HOW IT’S DONE

Here’s the entire page, minus my comments. Take a few minutes to learn as much as you can from this, then I’ll break it down into smaller pieces.

<HTML>
<HEAD>

<SCRIPT LANGUAGE=”JavaScript”>
<!– Beginning of JavaScript -

function MsgBox (textstring) {
alert (textstring) }

// – End of JavaScript – –>
</SCRIPT>

</HEAD>

<BODY>

<FORM>
<INPUT NAME=”text1″ TYPE=Text>
<INPUT NAME=”submit” TYPE=Button VALUE=”Show Me” onClick=”MsgBox(form.text1.value)“>
</FORM>

</BODY>
</HTML>

Categories: JAVA SCRIPT

Tutorials for Drupal

October 23, 2009 Leave a comment

A. Getting Started
There are a number of ways to set up a test environment on your own local computer.
Numerous applications and tutorials for a variety of operating systems are located in the
Setting up a development environment section of the handbook.
Reasons to run a local development server:
Developing locally allows you to work when not online.
Getting your local server running, even if it is with a simple installation like WAMP,
will help you start thinking in terms of server processes and databases. As you get
deeper into Drupal that knowledge will pay off.
Everything you put on the web is searched, archived and hangs around for a long
time. Do you want your inevitable learning mistakes displayed for the world to see on
Google?
This tutorial uses the example of building a site on a PC with Windows using the
DeveloperSide.net package.
This package has already integrated the following things:
Apache 2.2 HTTP Server
MySQL 5.0 Database
PHP 5.2 and Perl 5.8 Scripting Languages
GUI WAMP-stack Controller
Dynamic DNS Client
Tomcat Servlet/JSP Container
mod_aspdotnet ASP.NET Host Interface
OpenSSL Cryptography Toolkit
mod_security Web Application Firewall
phpMyAdmin MySQL Administration
Joomla
Drupal
WordPress
MediaWiki
phpBB
Do note that any package, like the DeveloperSide one, that includes Drupal for you may
not always have the latest secure version of Drupal. It is, therefore, recommended that you
check the version immediately and upgrade Drupal if needed when using these packages.
I followed their instructions, which built me a working system! For more instructions see
the Web.Developer page in the development environment section. I don’t remember if it
was automatic or not, but you will find it useful to have the “Web-Developer Controller”
icon on your desk top.
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
4 of 39 25.10.2008 18:42
The only “fly in the ointment” was that when I went to the Drupal web site to start pulling
my modules and themes, there was a big announcement on the front page saying that a
new security release for Drupal 5 had been released and was highly recommended.
I downloaded the latest stable release. I then unzipped it (using WinZip).
Of course, that created a directory called “Drupal-5.1,” (the latest version at the time this
was written) but the other software I had installed was looking for a directory called
“Drupal.” Well, by getting Apache and its services shut down, I managed to rename the
two directories so that 5.1 was now called “Drupal.” It worked! I now had a running 5.1
system!
If you have not set up your site using a package that includes Drupal, it is still very easy to
install in a few minutes. You can find complete instructions in the handbook Getting
Started section under the version number you are installing. Here are the directions for
Drupal 5.
B. Basic Configuration
Whether you run one site or several, there are some basic things you should do right now.
Here’s what I do right off the bat; the advantage to doing it in the “root” database is that
when I make copies for my other sites this has already been done. I’d give you a link to
something on the Drupal site, but I never found anything like this.
Go to Administer>>User management>>Roles and create an “1. administrator” role.
Go to Administer>>User management>>Users and create a user entry for yourself. This allows you
to test the site by changing your role to meet your needs.
2.
Go to Administer>>User management>>Access control and allow the “administrator” role to do
everything.
3.
While you’re there, go ahead and set what the “authenticated users” (logged in) and
“anonymous user” (not logged in) can do, such as using your contact form. This is not
engraved in stone; you can change it any time you want.
4.
Go to the Administer>>Site configuration>>Site information page and, near the bottom, set the
“Default front page” to “node.” As long as you’re on this page, set basic defaults for
the other fields. I don’t know about everyone, but I don’t like, when I visit a site, being
called “Anonymous” so I change the designation to “Visitor.”
5.
If there are any modules (core or contributed) that you use on all sites, go ahead and
enable them now ((Administer>>Site building>>Modules). For example, you will probably use
“Page” on all sites, and maybe “Story.” I am finding more and more uses for “Book.”
6.
I do recommend turning on (enabling) the “Path” core module so you can use
“normal” names for your pages.
If you want to use the contact form to email anyone from the site, be sure to enable
the “Contact” module.
7. The same goes for themes.
There are a few things I recommend that you do in all your databases, so this is a good
time to do it:
Turn on “CLEAN URLS” to make your site more user friendly. Go to Administer>>Site
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
5 of 39 25.10.2008 18:42
configuration>>Clean URLs. At the bottom of the verbiage there is a link to run the “Clean
URLs Test.” If it passes, then the “Enable” radio button will un-dim. Click on that. (If
the URLs stop working for some reason here are instructions to unset clean URLs.)
In order for me to create any kind of content, I go to Administer>>Site configuration>>Input
formats and set “Full HTML” as the default until I get the site ready to go live. Then I
still allow administrators (like my other ID) to use that format. Do this now and you
will avoid a very common problem with building your site.
I don’t like having “Promoted to front page” as a default for content, so I go to
Administer>>Content management>>Content types and turn that off – in each format.
While you’re there, decide on your default comment mode. Go to Administer>>Content
management>>Comments>>Settings and set the comments to be entered on a “separate page” and
make sure that “Preview comment” is set to “Required.”
Now, let’s turn on the Contact form so your users can send you a message. Go to
Administer>>Site building>>Menus and locate the “Contact” item. Click on the “enable” link.
Remember that later on you will want to go to Administer>>Site building>>Contact form and
finish setting that up.
C. Creating Multiple Sites On a Local
Computer
Need another test site? Here’s how to do it the “easy” way. [Hint: if creating multiple sites
is desirable make a list of the desired sites before reading through these instructions
completely. Some steps can be done in bulk to save time.]
Why create extra sites? In addition to my having several sites running already, I had some
ideas in the back of my head, not the least of which being a site where I could document
everything I do (like this book). I also had some ideas for other sites that I might put up in
the future. So before you totally pooh-pooh the idea, give it a few minutes’ thought. And
you can always change your mind later; it just might be a bit messier then.
At the very least, I would create a “working” site other than my “root” site. This makes it
easier to start all over again if you get totally out of control later on.
This may look like a long process, but it’s deceiving because I spell it out in detail. It is
expanded and updated from the post “Running multiple sites on a local PC (localhost) from
a single codebase, using Windows.” For more details on the “official” stance on the sites
directories, read Setup of /sites directory for multi-site.
If you want to get deeper into creating multiple sites either locally or on your server, you
can search the forums at drupal.org with the term “multi-site”; there is also a group
devoted to this subject at http://groups.drupal.org/multisite. Within the Handbooks, there
is a good section: Multi-site installation and set-up.
Open phpMyAdmin (using “other” in Web-Developer Controller)
start bulk loop 1
On the left, select the Drupal51 database. This is the one that was created by the
package installation.
Click on “Operations”
Scroll down to “Copy Database to:”
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
6 of 39 25.10.2008 18:42
Enter the new database name.
Verify that the radio buttons are clicked for:
Structure and data
CREATE DATABASE before copying
Switch to copied database
Click on the Go button just below this area.
When the copy is complete, click on “SQL”.
In the “Run SQL query/queries on database” box, enter:
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON
databasename.* TO ‘admin’@'localhost’ IDENTIFIED BY ‘superpw’;
FLUSH PRIVILEGES;
admin is what I call my administrative role (this is the “super-user” name);
superpw is the password for this user (I tend to use the same one for all my databases
to make it easy).
Hint: I created and saved this in c:/www/drupal/grant.txt so I could copy and paste.
Change databasename to the new database’s name.
end bulk loop 1
Close phpMyAdmin.
Go to the www/Drupal/sites directory.
start bulk loop 2
Copy one of the site folders (e.g. default) and name it for your new site.
Open the directory, then open the settings.php file in Notepad.
Change the $db_url and $base_url lines. The $db_url line should have the name of the
database you just created. The $base_url will be how you want to access the site.
Close the file.
If you are going to have site-specific modules or themes, go ahead and create
directories in this site to hold them (named “modules” and “themes”).
end bulk loop 2
Navigate to the /www/Apache22/conf folder.
Locate and open the “httpd.conf” file (Hint: I always make a copy of things I’m about
to change, just in case I mess up.)
I did notice that my version of Apache sets index.html ahead of index.php, so don’t have an
index.html in your directory.
Find the line that says “# Virtual hosts.” Remove the “#” from the next line. This
allows you to make all your other changes in a separate, and less dangerous file.
Save it.
Navigate to the /www/Apache22/conf/extra folder.
Open the httpd-vhosts.conf file.
At the bottom of the existing list, comment out (“#”) the examples.
start bulk loop 3
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
7 of 39 25.10.2008 18:42
At the bottom of the existing list, enter:
<VirtualHost *:80>
DocumentRoot /www/drupal/
ServerName databasename
</VirtualHost>
Change databasename to the new database’s name.
end bulk loop 3
Close the file.
Navigate to the /windows/system32/drivers/etc folder.
Open the Hosts file with Notepad. Hint: these two steps can be done by using “other”
in Web-Developer Controller.
start bulk loop 4
Add a line that says:
127.0.0.1 databasename
Change databasename to the new database’s name.
end bulk loop 4
Close the file.
Go back to Web-Developer Controller.
Click on Apache2 (top left).
Click the Stop Service button.
Wait for it to change to “stopped.”
Click the Start Service button
Wait for it to say “running.”
Go for it. You can now start the browser and enter http://databasename.
For more details on directories for multiple sites, see Setup of /sites directory for multi-site.
D. Error Pages
Occasionally, a user may do something that confuses Drupal, such as typing a wrong page
name or trying to access content they shouldn’t. These will generate 404 and 403 errors,
respectively.
A recent SEO newsletter, they mentioned the value of letting Drupal handle these errors:
Your unique 404 error page should look like a regular page of your site. It should
include your site’s header, footer and navigation bar so that the site visitor can
easily click on another area of your site. The content of this unique 404 error
page should contain text explaining that the page selected is no longer available
along with contact information so the site visitor has the option of emailing or
calling your company.
This was one of those “Duh” moments for me. How obvious it is that you should make it
easy for the user to get “back into” your site.
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
8 of 39 25.10.2008 18:42
The same more or less goes for the “access denied” (403) error message. Let them know
they did a no-no and try to explain why.
Just go to “Create content” and select “Page.” I title them “Access Denied” and “Page Not
Found” but you can call them whatever makes sense to you and your users. When you
submit them, note the node ids. Then go to Administer >> Site Configuration >> Error Handling and
enter “node/nnn” in the appropriate boxes.
Page Not Found
Here’s the HTML for my 404 page:
<p>Sorry! The page you were looking for no longer exists. We redesigned our site and many of the pages have
changed.</p>
<p>&nbsp;</p>
<p>If you are unable to find something on our new site or have a question about our site or services feel free to
<a href=”/contact”>contact us</a>.</p>
<p>&nbsp;</p>
<p>–Webmistress</p>
Access Denied
Here’s the HTML for my 403 page:
<p>We’re sorry, but you must have permission to view the page you requested.</p>
<p>&nbsp;</p>
<p>If you are already a registered member of this site, please try <a href=”user”>logging in</a>.</p>
<p>&nbsp;</p>
<p>If you are not a member, you need to <a href=”/join_us”>join us</a>.</p>
<p>&nbsp;</p>
<p>If you have any questions about our site or group, please feel free to <a href=”/contact”>contact us</a>.</p>
<p>&nbsp;</p>
<p>–Webmistress</p>
Don’t worry that you haven’t created the “join_us” page yet. This is an advantage to having
URL Alias support (the Path module) enabled. Just add to your to-do list to create this page
when you get to the “Creating Content” step a few chapters later in this book.
E. Accessing Your Test Site(s)
Okay, great, now we have all that software installed. But how do we use it?
First, open the “Web-Developer Controller” that you put on the desk top. Look at the top
left. You want to see, and should, if Apache and MySQL are running. If they are, you’re just
about ready. If not, select Apache, then click on the “Start Service” button. Within a few
seconds it should change to “Running.” Now select “MySQL” and start it.
Fabulous, we have the software ready for us. Now let’s get us ready.
Fire up your favorite browser. In the Address field type in http://localhost/drupal/ to access
your “root” database. Since you’ve done everything right, you’re now into your Drupal
database.
Congratulations! Now the work begins.
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
9 of 39 25.10.2008 18:42
F. Adding Modules and Themes
Let me first say that a newbie shouldn’t worry a lot about adding modules and themes at
first. Work on the basics of your site first, then worry about add-ons.
Themes are largely a matter of taste. For example, I have no idea why anyone would use a
“fixed width” theme, but lots of people do. One nice thing about themes are they are pretty
much independent of your content (later on you can look at the many submissions that are
dependent on content).
Contributed modules are ways to add or extend functionality of your site. The only module
I, personally, consider necessary is the Nodewords (a.k.a Meta Tags) module; in my
opinion, it should be promoted to “core” status. This one allows you to add the “content,”
“keywords,” and “robots” meta tags to your pages. This is useful if you’re interested in your
search engine rankings. You will also find that many contributed modules also require the
Views module; I go ahead and make that a standard one for my sites.
Now, if you experiment with different themes and modules, as I know you will, despite my
suggestions, you should also look at the Update Status (core in D6) and Site
Documentation modules to make sure you are current and to document and clean up the
mess your experimentation will make. Here are some suggestions on choosing the release:
Strong stomach?
Installation
Installing a module or theme is pretty much the same until you get to enabling them. Now
keep in mind that I use a Windows based PC (development) and Linux servers (on my live
sites).
Go to the Drupal site and click on the “Downloads” tab. Then select either “Modules”
or “Themes” depending on what you’re after.
1.
Locate the module 2. or theme you want.
Make sure there is a version for the version of Drupal that you are using. D5 modules
and themes will not work on D6.
3.
I always click on “Find out more” and read the stuff again. This gives you the chance
to see if there is support for your release of Drupal. You can also look at pending bugs
and feature requests – it might change your mind.
4.
5. Download the proper release. (I put them in a Drupal folder in “My Downloads.”)
Unzip the downloaded file (I use WinZip). It may tell you that there is only one file in
the zipped file; click “yes” or “OK.”
6.
Extract the code to to your /sites/sitename/modules or themes folder. If you are not running
multiple sites, this would be /sites/all/modules or themes.
7.
8. That’s it! Now you need to enable it.
For advanced users
If you have access to a Unix shell (e.g. SSH), the following series of commands will
download and extract the files directly to your server.
Before you start, use the pwd (print working directory) command to confirm that you are in
the correct directory (e.g. modules). If not, use the ls (list directory) and cd (change
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
10 of 39 25.10.2008 18:42
directory) commands to navigate to the correct directory.
Steps:
Step Download Archive:
wget http://copy_and_paste_archive_url/sitedoc-5.x-1.x-dev.tar.gz
1.
Step Uncompress Archive: tar zxvf sitedoc-2. 5.x-1.x-dev.tar.gz
3. Step Delete/Remove Archive: rm sitedoc-5.x-1.x-dev.tar.gz
Note: the module sitedoc-5.x-1.x-dev.tar.gz is taken here as example please check the current
version and or substitute with your preferred module.
Modules
Modules
You enable a module at Administer>>Site building>>Modules. The non-core modules are listed
farther down. With 5.x, they now show you some of the inter-module dependencies. I turn
them on and “Save configuration” in order of the dependencies. For example, “Views UI”
requires “Views”, so I turn on “Views” first, save the configuration, then turn on “Views
UI.” and save again.
Most modules introduce some kind of menu items. Those will generally appear
automatically when the modules is enabled. A few menu items will not show up until the
permissions are set (the next step). And even fewer require you to take action to add the
menu items, but the module will have instructions on how to do that.
Ah, now the real work begins. Go to Administer>>User management>>Access control to select who can
use the features of the new module.
If the module introduced new content types, go to Administer>>Content management>>Content types and
configure them. Don’t forget this may also affect your “Input formats” (Administer>>Site
configuration>>Input formats) and “Categories” (or taxonomy, Administer>>Content management>>Categories);
you’ll have to check those too.
Okay, now you can start using the new module.
This Site
My documentation site is a relatively “vanilla” implementation of Drupal.
Blog
Book
Comment
Contact
Help
Menu
Path
Codefilter – Provides tags for automatically escaping and
formatting large pieces of code.
Meta Tags (Nodewords) – Allows users to add meta tags, eg
keywords or description.
Site Documentation – Documents and cleans up your
configuration.
To get some idea of what modules are available, check these links: module handbook and
contributed modules handbook.
Themes
You enable a theme at Administer>>Site building>>Themes
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
11 of 39 25.10.2008 18:42
If it has never been enabled on this site, you will have to check the “enable” box and then
click the “Save configuration” button at the bottom.
To set up how the theme works, click on the “Configure” link (not the tab at the top).
Fill in the fields.
Save the configuration.
Don’t leave the page yet.
Logo and Favorite Icon
Now use that “Configure” tab
I prefer to do this part under the “Global Settings” but it can be done theme-by-theme if
you prefer.
The “Default Logo” is that little picture (usually) in the upper left corner of the page. For
example, on the “Bluemarine” theme, it’s the Drupal logo.
If you want to change it, here’s how:
First, find out what size it is because you’ll want your own logo to be about the same.
(If you are comfortable with HTML and CSS you can also edit the theme’s code to
accommodate your logo rather than resizing the image. How to edit theme code is not
covered in this beginner’s guide.)
1.
Bluemarine 48 55
Chameleon 49 57
Garland 64 73
Minelli 64 73
Pushbutton 144 63
Fancy 80 80
Under “Logo image settings” either type in the path to your logo, or upload it from
your PC.
2.
Note: Neither one of those options turns off the “Use default logo” check box. You
must select the correct check box yourself.
3.
The “Shortcut icon” (a.k.a. the favorite icon, or “favicon.ico”) is the same way. If you
want to change this, you must specifically say, “Hey, Drupal, I’m changing this.”
4.
Now you click the “Save configuration” button. If you did this in “Global settings” it affects
all themes (assuming they behave properly); if you did it for a single theme, then only that
theme is changed.
For a list of all available themes, check Themes.
HINT: Going to make a few (or a lot) of changes to a standard theme? Think about copying
it over to your /sites/sitename/themes/ folder and renaming it. Then you can do anything you
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
12 of 39 25.10.2008 18:42
want and still be able to undo it easily by recopying. If the changes ae a bit bigger, think
about contributing it back to the community (with your name, of course).
G. Creating Content
“Wow, I’ve done all this and I still don’t have any content on my site!” Well, let’s fix that.
First, let me explain that the page your visitor sees first upon entering your site is usually
called the “home” page. Drupal calls this the “front” page, much like a newspaper. This
page is special to Drupal. I know you’re in a hurry, but read about both “pages” and
“stories” before you decide which to use to create your front (home) page.
Content Types
Page
Drupal says, “If you want to add a static page, like a contact page or an about page, use a
page.” If you’re used to building web sites with HTML, this is what you’ve done in the past.
In general a “page” is going to stand on its own and will probably have a menu entry. You
may also later add it into a book. When I created my first two sites (based on former static
HTML sites, I made the front page a “page;” I have since changed to a “story.”
Story
Drupal says, “Stories are articles in their simplest form: they have a title, a teaser and a
body, but can be extended by other modules. The teaser is part of the body too. Stories
may be used as a personal blog or for news articles.”
Okay, you’ve seen the Drupal site and noticed that there are “pieces” all over the place.
Look at the front page; you’ll see several announcements with space between them – those
are “stories.”
I have now switched my sites to use stories on the front page. The “welcome” message is
one story. I have an announcement story node that any of my admins can edit. If you want
to have weather or cartoons, a story is a good idea. Another use is if you are on a net ring -
put the ring links into a story.
Book Page
Drupal says, “A book is a collaborative writing effort: users can collaborate writing the
pages of the book, positioning the pages in the right order, and reviewing or modifying
pages previously written. So when you have some information to share or when you read a
page of the book and you didn’t like it, or if you think a certain page could have been
written better, you can do something about it.”
Another way to use a book is to collect related information together. A book has its own
navigation, so it can also be used to de-clutter your menu.
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
13 of 39 25.10.2008 18:42
Blog Entry
You probably already know what a blog is, but just in case: A blog is a diary, collection of
thoughts, or other time-ordered content. The Blog Entry content type is added by the blog
module. The blog module allows you to have a multi-user blog, meaning that every user can
have their own personal blog. This adds titles and breadcrumbs to indicate the blog
authors’ names. Generally if you only have a single blog for a site then it is best to use the
Story node for blog entries.
So have you decided what kind of content you want? No, okay, just start with a page; it’s
easy. As you go create your content, be thinking about the menu as well.
NOTE: If you want to set your front page (Administer >> Site configuration >> Site
information) as “node,” then you need to have at least one piece of content marked as
“promoted to front page.” If you don’t do this, you will keep getting that “Welcome to your
new Drupal site” message.
Another Handbook section you may find useful is Creating new content.
Adding Images to your text
There is a choice of facilities for adding images to text items, with pros and cons of each.
1. The Image module, and associated features. Makes each image into a Drupal node,
which ads a lot of capability.
· Image_Attach, which adds a separate image field to the target node, pointing at the
image node. Provides simple image upload, but little other control.
· Image_Assist which embeds the image in a text field. Provides visual image selector,
upload, and control over size and left/right float. Adds necessary HTML to text field.
· drupalimage plug-in to TinyMCE editor which makes Image Assist work with a TinyMCE
field, which displays the result as a WYSIWYG image (though not styled fully according to
your theme).
Also untested further features, including:
· Bulk upload facility
· Interface with the Drupal Gallery support module.
· Similar interface to the Acidfree support module.
2. The CCK ImageField. Very similar to Image Attach, but just uploads image into a
filestore file, and again contains little extra control over e.g. sizes or styles. It is almost
invariably used with Imagecache to give fine control for resizing.
3. IMCE( demo at http://ufku.com/drupal/imce/demo). Provides facilities to upload and
search for images on the server. Functionally similar to the Image_Assist/drupalimage
combination, but the integration with TinyMCE is neater for inserting images, and there is
more control over the attributes of the image once inserted. BUT the image filing and
select window does not look so nice – to the point of affecting usability, and there are bad
things on the Blogs about the associated gallery function.
4. Or go to FCK Editor. From the demo seems as good an editor as TinyMCE, and has its
own image upload and filing mechanism. But:
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
14 of 39 25.10.2008 18:42
· No automatic creation of thumbnails etc. (cf Drupal Image)
· Images are simple separate filestore files – may be a benefit depending on what one
wants?
I have oscillated quite a bit, but (at the moment) am going with the Image module:
· Install the Image module as normal.
· Do the stuff in http://mybesinformatik.com/tinymce-and-drupal5 to add the drupalimage
plugin to TinyMCE.
· Tune the settings in the TinyMCE Profile to show the features required.
· Create a Taxonomy to allow tagging of images for easier retrieval.
Front pages
After following the next few steps, you will be able to easily add / change your front page
anytime in the future.
1. Creating your front page
After logging in as Administrator, select
Create content > Page
from the left menubar, and create your own content that you would like to publish as a
front page. If you are done, hit „Submit” to see the results. Notice that the current URL
(the path to your newly created page) looks like this
http://www.example.com/?q=node/# (normal)
http://www.example.com/node/# (using clean URLs)
where # means a number. We will need that number, so write that down somewhere or just
try to remember that.
2. Front pages
Now you can either choose to
2.1. Set a single page as your front page or
2.2. Promote your page to the front page, this way adding it to the top of the front
page posts. (Only the first 5-10 lines will be published there (as a preview), you will
have to click on it to see the whole page).
2.3. Use the Front module to fully customize your front pages (theming, different user
roles…)
2.1. Setting your page as Front page
After creating your custom page, select
Administer > Site Configuration > Site Information
At the bottom of this page where it says „Default front page” you will have something like
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
15 of 39 25.10.2008 18:42
this
http://www.example.com/?q= (normal)
http://www.example.com/ (using clean URLs)
and an input field next to it. That is where you have to enter
node/#
where # is the node number that you previously wrote down. By pressing „Save
configuration” your front page automatically becomes the previously created page. You can
reset that any time you want, by entering only
node
into the input field. (That is the default value).
2.2. Promote your page as Front page
If you want to promote your page to the front page, you should go back to step 1. but now
don’t press “Submit”, or edit your newly created page (navigate to this address)
http://www.example.com/?q=node/#/edit (normal)
http://www.example.com/node/#/edit (using clean URLs)
where # is the node number.
Either way, at the bottom you will find a drop down menu called „Publishing options”,
there you will have to check the „Promoted to front page” checkbox and that’s it. Press
„Submit”.
2.3. Front pages with Front Module
If you really need more control over your front page, you can use the Front module to
Set a different theme 1. to your front page
2. Set different front pages depending on user roles (admin, anonymous, authenticated)
3. Insert custom php snippets into the front page
You can find the Front module at: http://drupal.org/project/front
After installing the Front module, select
Administer > Site configuration > Advanced front page settings
There the drop down menus are pretty self-explaining. If you click on any of the „Front
page for _user role_” you will find
Body: you can input text, html and even php snippets that you want to display
Select Type: you can set other user roles to have the same front page as this, have
default or custom themes be applied to it, etc.
Redirect to: you can set a location where users should be redirected to
If you are satisfied with your settings, press „Save configuration” and you are done.
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
16 of 39 25.10.2008 18:42
G1. Creating a Page
Click on “Create content” in the menu, then select what kind.
The title and body are pretty self-explanatory. Below these are a number of collapsible
fields. “Input format” controls what you can put into the page; I’m assuming you are the
“super-user” (user/1), so give yourself the priviledge of “Full HTML.”
If you have Nodewords installed, the next section is “Meta Tags.” It’s pretty well
documented.
Use the log message to provide information that might be useful to other authors who may
edit your document later, or provide your rationale for making edits to your own or other
people’s content. The log message is not visible to users without the appropriate content
editing rights.
As logs are recorded on a per-revision basis, each time you revise your content and make a
log, the log message is stored with that particular revision of the article only. If you are
have editing rights over a page you can see a list of revisions (if you selected the option to
make a revision when you edited the document) and their associated log messages by
clicking on the revisions tab.
Hopefully, you already set your default “Comment settings” but the front page rarely
deserves comments, so you can disable them.
If you turned on the “Path” core module, you’ll have URL path settings next. You can enter
a “normal” name here rather than being required to use “node/2″ when you refer to it later
on. Hint: if you are converting a site that was static pages, you might want to go ahead
and add “.htm” or “.html” to the name so that the search engines will continue to find the
page.
“Menu settings” is the next section. “Title” is what will show in the menu normally.
“Description” will show when the user hovers the cursor over the menu item. “Parent item”
allows you to create multi-level menus that collapse and expand. “Weight” allows you to set
a relative position within the menu; unfortunately, some Drupal core items are hard-coded
at 0.
Chances are you won’t need “Authoring information” unless you want to attribute the page
to someone else. The other use for this section is to control the page or story order when
they are based on the time and date it was created.
Finally, “Publishing options,” which you set defaults for earlier, right? You want the page
“Published” so it will show up. If this is your “Welcome” page, you’ll want it “Promoted to
front page.”
“Submit” it.
Congratulations, you now have some content on your site!
G2. Creating a Story
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
17 of 39 25.10.2008 18:42
Most of what goes for a page is also true for a story. You can largely consider the two types
to be interchangeable, and it is goodness to have at least two content types because
conflicts can arise in the way content types are used (for example, taxonomy “collisions”).
Stories have a “teaser” or opening statement intended to grab the reader’s attention. The
length of the teaser is set in one of two ways:
In Administer>>Content management>>Post settings. The default there is 600 characters. You can
change that.
By specifically identifying a break point with < !–break–> [without the space] in your
content (before the default limit).
Note: You may see some places that tell you to use <break> to set a teaser point. This
was originally changed in 5.0 and created a considerable controversy, so it was
backed out.
A story probably shouldn’t have a menu entry. If you use the general “convention” that a
“page” is for static or generated content that stands alone, and “story” is for collections of
related content (e.g. RSS feeds, newsletter articles, press releases, etc.), then a story is
usually going to be displayed with other stories, so which one would be the menu item?
Generally the menu for a set of stories will be a description of how they are selected for
display.
You may want to promote the story to the front page. For your “Welcome” message, you
probably also want to make it “Sticky at top of lists.” Unfortunately, there is no core
“weight” feature, so you have to play with the dates and times in the “Authoring” section to
control the order. (Or you can use the Weight module.)
What’s a Teaser?
This is from a post by zoon_unit on January 10, 2007.
A “teaser” is essentially a snippet of text designed to tell the user the content of a post
without reading the entire post. Since most writers have embraced the common
journalistic style of explaining the nature of an article in the first paragraph, teasers work
well for most articles.
Here’s what happens:
A node contains 1. an entire article.
Drupal’s “teaser” function, “node_teaser,” strips the first x number of characters from
the article and makes it available as content. The exact length is determined by the
value set in Drupal’s Administer » Content management >> Post settings.
2.
So, you list a bunch of articles on a page. You want the articles to display only a
snippet of text from the full article, so that you can fit a bunch of articles on a page
without requiring the user to page down through tons of text. If the user likes the
“teaser” content of the article, they will click on the article’s title and see the full
content of the article on its own page. In a sense, teasers function like summaries of
an article, except that the software decides where to cut off the text. If you want to
determine where a teaser article ends, you can insert the comment tag to instruct
Drupal exactly where to fashion the break between full text and teaser text.
3.
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
18 of 39 25.10.2008 18:42
G3. Creating a Book Page
Generally, I only create one book page for each book. This is the first one, usually the
introduction. All other pages will be added as “Child pages” (to be accurate, child pages
will still have the “book page” content type set for them).
In addition to the things I said about pages, a book page has a “Parent.” For the first page,
this will be “<top-level>.” If you use “Add child page” the “Parent.” selection should be
already filled in with the book’s name. If you create another book page, you would need to
make sure you properly select which book or page the new one is to be made a child of.
The top page of the book probably deserves a menu entry. The rest do not, unless they are
really special. Remember, a book has its own navigation.
You are currently reading a “book.”
G4. Creating a Blog entry
Blog entries are a little different. Assuming you enabled the “Blog” module, you should see
a “My blog” entry in your navigation menu. When you click on that, there will be a “Post
new blog entry” link on that page.
If the blog is a diary, you probably want to use the date for the title.
If it’s a collection of thought, give it a meaningful title.
Type in the content of the entry.
Your blog will always show the most recent entries on the beginning page when visitors
view it.
H. Custom Blocks
Following is a simple example of custom block. For more information on blocks in general,
see the Blocks page of the handbook.
Adding A ‘Contact Information’ Block
A business or support group should always let people know how to contact them. One easy
thing is to include your mailing address on your pages. This is about the easiest kind of
block to start with.
Go to Administer>>Site building>>Blocks. It should already be sitting on your
default theme, but if not, select the right one.
1.
Click on the 2. “Add block” tab.
3. Fill in the “Description” and “Body.” Here’s a sample body:
Example Organization<br>
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
19 of 39 25.10.2008 18:42
123 Main St.<br>
Mytown, State Zip<br>
USA<br>
(123) 456-7890
4. Save the block.
5. Now you can “Configure” the block to add the block’s title and define it’s “Visibility”.
Follow the Configure link next to the block and enter “Contact Information” as the
Block’s title.
6.
Decide if you want to allow users to turn the block on or off, and, if so, which roles
should have that ability. You can leave this with no changes to allow everyone to see
it. Then choose which pages it will be shown on; Leave this empty to show the block
on all pages.
7.
8. Save the block.
Now you’re back on the block list. Find the block you just created in the list and
choose a “Region”. You can use the “Weight” parameter to set its position with in the
selected area; again, I like the address at the bottom, so I use a heavier weight.
9.
10. Click on the “Save blocks” button.
Adding a Last Updated Statement
It is fairly common practice, especially on a group site to let the visitors know when the
site was last updated. This example requires you, the webmaster or administrator
(sometimes called the “super user”) to maintain the block. There are ways to automate this,
but for right now, we’ll do this manually.
Follow the same process as for the ‘Contact Information’ block, giving this one a
slightly heavier weight to sink it to the bottom.
<em>Site Late Updated on Feb. 12, 2007</em>
For this block, lets set it to show on every page except the home (front) page. So
under “Page specific visibility settings,” I clicked on the “Show on every page except
the listed pages.” radio button, and entered <front> in the pages box.
Creating a Newest Posts Block
Creating a newest posts block is easy using Views. With slight modification you can use
this to list comments or list nodes by score if you have a rating module installed. The
information below is for version 5.X of Drupal. Things may be different in Drupal 6.X
Step 1 – Installing Views
Download install the Views Module. Follow the instruction that come with it.
Step 2 – Block Title
Determine what to call this block.
Step 3 – Number of Posts
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
20 of 39 25.10.2008 18:42
Determine how many posts you want in the block. You might also want to decide what
information you want to be displayed. For this tutorial we are going to display titles, but
you could display the teaser as well. The amount of information that is displayed could
affect your choice as to the number of posts to display.
Step 4 – Starting Views
Login to the admin page of your Drupal site and go to Site Building > Views.
Step 5 – Block Basic Information
Once you are on the Administer Views page, click on add. Fill in the basic information -
Name, Description, and Access Privileges. The name must be alphanumeric and you must
use underscores for spaces.
Step 6 – Basic Block Setting
Creating the block is very easy. Move down the page until you see word “Block” as a
hyperlink. Clicking on it will expand the block section.
Click on the check-box “Provide Block”. This means that Views will provide a block for you.
You will find it in the top of the block section.
Now we want to tell it how to display the output. You have several options but for this the
best is “list View”. Since we are just going to list the titles. If you wanted more information,
you could use the “Teaser List” to provide the name and description of the post. So, where
it says “List Type” you will select “List View”
Finally, you need to tell how many nodes you want in the list. Just fill in “Nodes per Block”
with the number that you want. If you are using a theme like “Denver”, you might want to
use 5 for the top regions. If you are placing in a side bat you could use 10 or more.
Depends on how fast your content changes.
Step 7 – Selecting Fields
After that is finished, you want to tell views what field you want to display. The next
section below “Block” is the “Fields” section. Click on “Fields” to open it. Then select the
field that you want. Then click on the “Add Field” button. For this example, we want to
select the title of the node. So you want to look for “Node : Title”. If you wish you can give
it a label like “Newest Posts” or “Latest News”.
Step 8 – Filtering
You may not want every thing showing in your latest posts. You can limit it. For that you
have to go down the page to “Filters”. Click on it to reveal the filtering options. This is
where you can select the content type(s) to show in the block. Where it says “Add Filer”
select “Node : Type” and then click on the “Add Filter” button. For the operator you want
to select “Is One Of”. Then you pick the content type from the “Value” drop down list.
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
21 of 39 25.10.2008 18:42
Step 9 – Saving View
Once you are all done on this page, save your view.
Step 10 – Displaying the Block
Go to Site Building > Blocks. Here you will see all the blocks. Find your newly created one
and decide what region to place it. Depending on your theme, you may have a lot of
regions or very few few regions.
Once it is assigned to a region, set the weight. The larger the weight value, the farther
down the block will be on the page.
Once the weight is set, configure the block. This will allow you to decide who see the block
and on what pages it shows on. A good place to place a listing of newest posts is on the
front page. To do that, you want to find “Pages” and put in the text area. Then right above
select the “Show only on selected pages” option.
Once you are done making all your setting for this block, save this block.
Notes
You can use this method to show your content in other ways. You could show the highest
rated content or most recent comments.
You may want to have a special page for listing your 25 highest rated or 25 newest posts.
There are special modules that allow you to do this. You can use “Insert View” or
“Viewfield” to put views in pages.
Check out the modules for Views at http://drupal.org/project/Modules/category/89
I. Working with the Menu
Introduction
This will not be an exhaustive piece on the subject of menus. My main point will be to start
you on building your menu and giving you a flavor for how it works. A more complete guide
to menus can be found at Creating a menu structure.
As we all know the menu, or navigation system, can make or break a web site. It must be
easy to follow, often referred to as “intuitive.” It must be complete, yet compact.
There is a lot of content on the Drupal site on menus. Most newbies have trouble
understanding it all. I’ve been using Drupal for just over a month as I write this and I still
have a long way to go on completely understanding menus.
For beginners it can be very confusing to understand the difference between menus and
categories. The menu is a navigation system and categories is a system to order content
data. So menus is to arrive at content and categories to order it. Initially to understand
Drupal well, you have to see these as two separate things.
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
22 of 39 25.10.2008 18:42
With a menu you can point directly to a node, like a page or a story, but you can also point
to a term in a category, which would show you a summary list of stories or pages.
How To Menu
Drupal offers three primary ways, which may be combined, to provide your users with site
navigation.
Textual menu – this is the “standard” line-by-line type of menu, like what you see on
most sites, including mine. It can be enhanced in a few ways, such as using a CSS or
separate book navigation (as I have done here).
1.
Tabbed menu – becoming more popular because it’s a little more “gee-whiz” in its
presentation. It is debatable as to whether it is any more effective for your visitors. In
Drupal, it is divided into “Primary” (the tabs you always see) and “Secondary” (the
part that drops down, or slides out). Not all themes support secondary links.
2.
Books – Books are organized separately from menus, but have their own navigation,
which you can see on this site. See my section Creating a Book Page.
3.
Textual Menu
The textual navigation is the easiest to understand. As a matter of fact, I still don’t
understand how to make the “secondary” part of tabbed navigation work the way a lot of
people think it should (drop down).
You may see the terms “primary links” and “secondary links” in many posts. This is one
area where I find the Drupal documentation confusing (at best). While they sounded great,
and I am now using them, they may not be the best thing for someone just starting out.
Stick to the standard “Navigation” menu until you have a better feel; you can always go
back and change this later.
For the most part, the “standard” menu is best built as you create content, but may require
a little tweaking as you see how it lays out.
When you create a page, story, blog, or book page, one of the fields that you may (should)
fill in before submitting, is the menu entry (if the node is to have one). You have the “title”
(what is to appear in the menu as people see it) and a “description” (what they will see if
they hover the cursor over that entry).
I rarely worry about the “weight” until I see how it shows up in the menu. At that point,
you can either go back and edit the content you created or go to Administer >> Site building >>
Menus and edit it there.
Okay, that was the easy part. Now let’s say you want this particular content listed in the
menu as a
child of some other page. No problem! Let’s say you have a subject’s introductory page
already listed in the menu, for example “Family History.” The page you’re creating is
“1860-1899.” When you build the menu entry, you’ll notice a selection box labeled “Parent
Item.” Scroll down the list until you find “Family History.” Now when you submit this page,
it will be a child of “Family History,” making that item an expandable menu item. You just
created a hierarchical menu!
Tabbed Menu
The Drupal Cookbook (for beginners) http://drupal.org/book/export/html/120612
23 of 39 25.10.2008 18:42
In those themes that support this technique, the “Primary” seems to get built automatically
as you build the “Navigation” menu, unless you specify a different menu set. I have no idea
yet how to make drop down “secondary” links part work – I think it requires a separate
module. I do know how to make the secondary links appear in a block, if they exist. I like
the way that works, but it may not be for everyone.
Books
The book “menu” is built automatically for you. The only thing you have to worry about is
the order of the entries (hint: weight).
The only “complicated” part is turning on the book navigation block, which is done at
Administer >> Site building >> Blocks. All you really need to do is to tell Drupal which region to
place it in and its relative weight. You can get fancy, if you want, with your style sheets.

Categories: DRUPAL

Basic Tutorials For AJAX

October 23, 2009 Leave a comment

JavaScript has had the XMLHttpRequest object for a good number of years now, but it’s really only started getting wide attention recently. All this attention is mostly due to some showoff web applications that make every developer who sees them think, “I want my site to do that!” But it also has to do with the spiffy, spiffy name given to it by the folks at AdaptivePath, who named this asynchronized application Ajax. Maybe you’ve heard of it?

A few high-profile Google applications in particular made a splash with Ajax:Suggest, and Maps, and Gmail. It’s also powers some of the core functionality in the user interface of the ever-so-popular photo sharing site Flickr. By now, Ajax has become a buzzword, and may even be the first JavaScript object with its own fan website. Date.com doesn’t count, although I did have a scintillating chat with a lady there once about the getTimeZoneoffset method.

What is Ajax?

So what is this fancy object that everybody wants a piece of? In brief, it’s a solution to one of the big annoyances of web interfaces. Generally, the user inputs some data or makes a choice, and clicks a button that sends the data to the server. The server takes a look at the data and sends back a whole new web page, which is loaded into the browser. Reloading a page every time you want to do something is annoying, disjunctive and time-consuming for the user. XMLHttpRequest moves that browser-server interaction to behind the scenes, so the user can just keep on playing with the same page, even while elements on the page are talking to the server! Go take a look at Google Suggest if I’ve lost you — it’s a nice, eloquent example of this.

JavaScript has always been able to sneakily trigger a server-side script without anything happening in the browser by using a few classic tricks. This one, for example:onSubmit='runascript = new Image(); runascript.src="http://www.wired.com/images/archiveyscript.php?" + this.value'. That sort of chicanery is good, maybe, for caching form data to a file on the server, but it doesn’t return any information to the JavaScript that calls it, so its usefulness is limited. Ajax, on the other hand, can get a full parcel of data back from the script it calls. Hence the “XML” part of the name – which really is just there for looks, kind of like the “Java” part of JavaScript, because the returned data can be plain text or whatever you like, if XML is overkill or just not your cup of tea.

This opens up millions of exciting possibilities. Every form submission, every JavaScript event, and heaven knows what else, can now interact with server-side databases and processing power. Data retrieval, password authentication, image generation – you name it, Ajax can trigger it.

Making Your Own

The potential of Ajax-enhanced web apps is limited only by your imagination – and by browser support. Mozilla-based browsers can do it, and Safari, and newer versions of Explorer, and Opera 8 but not Opera 7. It’s best to incorporate a fallback way of doing things for users who aren’t as cutting edge as you’d like them to be. Also, Explorer does things somewhat differently (of course) from all the other browsers, so it’s necessary to fork the code to account for the irritating little 80-odd percent of the population who use IE.

Let’s build a simple application that accepts input from the user, passes it to some PHP on the server that checks it against a database, and returns the result to the browser. It comes in three parts. First, we need an HTML form. This you’ve seen before:

<html>
 <head>
 <title>Report</title>
 <script type='text/javascript' src='xhr.js'></script> </head> <body> <form action="fallbackpage.php" method="post">
 <p>Welcome, student. Please enter your essay here:<textarea name="essay" id="essay">
 </textarea> <input type="submit" name="submit" value="Submit" onClick="return
 grade(this.form.essay.value);">
 </p>
 </form>
 </body>
 </html>

Note that, for users without support for our script (named xhr.js), the form will just submit to the fallback page at fallbackpage.php.

Next comes the JavaScript. This is the exciting part, so we’ll take it slow.

 function grade(essay) {

First, we initialize the object. We have to do it two ways, for different browsers.

    // Mozilla version
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    // IE version
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

Then, we escape the user input to make it URL-safe:

    essay=encodeURIComponent(essay);

and use the open method of the object to open a connection to the PHP script:

    xhr.open("POST","grade.php");

The method requires two arguments:first, the HTTP method (GET or POST); second, the URL of the script.

A quick HTTP header prepares the script for what it’s getting, and then the send method transmits the actual request:

 xhr.setRequestHeader(
      'Content-Type',
      'application/x-www-form-urlencoded; charset=UTF-8'); xhr.send(essay);

This last step isn’t necessary for GET requests, wherein all the data can be contained in the query string of the URL.

Getting Results

Now we’re ready to see if the HTTP request worked. The readyState property counts up from zero during the request, and shows 4 when the server page has loaded successfully.

 xhr.onreadystatechange=function() {
      if (xhr.readyState==4) {

If the request worked, then we can get the output of the server-side script by querying the responseText property, which contains a string. For more complex server script output, a responseXML property, which can hold a full document object of XML data, is also available.

      grade = xhr.responseText;
      alert ("Nice essay. Your grade is " + grade);
    }
    return false;
 }

Want to see all that in a pastable block? Here it is in a separate file.

Finally, the third component is the PHP script, which lives on the server and waits patiently for the JavaScript to pass it some juicy data. This example uses PHP, but any language you like — Ruby, Perl, C, ASP — can do as well. The core of this example script is a natural-language function called grade_essay() that grades student essays from 1 to 100, but I will redact that part to conserve space.

 <?php
 function grade_essay($essay) {
      return strlen($essay);
 }
 $essay = urldecode(implode(file('php://input')));
 $grade = grade_essay($essay);
 echo $grade;
 ?>
 

The php://input grabs the POST data, which gets put into a string, decoded and passed to the ingenious grading algorithm. The algorithm returns a numeric grade. Lastly, we just output the grade with echo – ordinarily, this would display in the browser, but since the PHP script is running “behind the scenes,” the string output is simply returned to the JavaScript that called it. If you need structured data, an XML document would be output with an echo statement in just the same way, but the content-type of the output page must be set to text/xml.

What the user sees is this:She types her essay into the text area in the browser, clicks Submit, and within instants an alert box pops up giving her a final grade on the essay. Invisibly, the essay has been sent to the server, read and evaluated by a team of PHP gnomes, and returned with a grade, without ever reloading the page. The user can modify her essay and resubmit it endlessly.

And that’s the gist of the almost magical XMLHttpRequest object! The example is simple, but the uses of the object can be elaborately, multifariously clever. If you need further inspiration and edification, a burgeoning number of examples are dotted around the Web:

Categories: AJAX

Mysql Tutorials

October 23, 2009 Leave a comment

Overview

MySQL is the world’s most popular open source, binary database server. It is capable of supporting over 50,000,000 records. SQL (Structured Query Language) is the language used to to communicate with the MySQL server. With the aid of this tutorial, you will learn how to build a RDBMS (Relational DataBase Management System). Table Joins, are the key to building efficient databases and harnessing the essential power of MySQL. Without table joins, a complex relational database will be as slow as a standard flat file database. PerlScripts JavaScripts.com will teach you how to utilise table joins and greatly increase the speed of your database queries. PerlScripts JavaScripts.com has taught lead programmers of other programming firms how to utilize the true power of MySQL.

What you need

You will need a web host that offers access to a MySQL server. Most hosts offer some sort of control panel, allowing you to set up and create your databases. If you need MySQL hosting, we have MySQL enabled plans from as little as $13.70. Once you have a host, you will need to ask them for certain information or use your control panel to create a database. Our Basic hosting plan ($13.70/mo) allows you to create up to 3 databases. The information you need is :

Path to the server

Database name

Username

Password

Connecting to the DB Server

Connecting to the database is easy. First you must load the MySQL module. Near the top of your script add this code :

use Mysql;

The line above will load the module ( or class of predefined subroutines ) named Mysql.pm into your script. To make database connections quick and easy, place your login details into a set of variables. These variables will be passed as arguments to the connect subroutine and should be declared near the top of your script or before using the connect command.

$DBHOST = “localhost”;
$DBNAME = “mydatabase”;
$DBUSER = “perlscripts”;
$DBPASS = “ywe6ywnq”;

You now need to begin constructing what is known as an object. Below is an example of how to utilize the connect subroutine.

$DB = Mysql->connect($DBHOST, $DBNAME, $DBUSER, $DBPASS);

Once the above code is executed, assuming the login details are correct, you are connected to the MySQL server. For demonstration purposes only, the code below could be used to select and print the first 100 records from a table named “employees”.

$DB = Mysql->connect($DBHOST, $DBNAME, $DBUSER, $DBPASS);
$qry = qq~SELECT * FROM employees WHERE id < 100~; while( @emps = $qry->fetchrow) {
print qq~
$emps[0], $emps[1], $emps[2]

~;
}

The code above, when translated into English, says “Connect to the server, select all columns from the table named employees where id is less than 100, then while the data is placed into an array called emps using the fetchrow method, print columns 1, 2 and 3 then a line break.”

Basic Queries

Some of the more popular queries are the easiest to execute, but can also be the most dangerous. For example, to delete a record, you might use :

DELETE FROM employees WHERE age > 35

However, if you forgot to enter a WHERE clause and condition, you would delete the entire table.

Advanced Queries

Advanced queries should be used in preference to extracting data then formatting it using another language. Many programmers either do not have the knowledge or just do not understand the power and speed of MySQL. The MySQL server is all about speed and efficiency. Manipulate and format the data as much as possible using MySQL before passing it on to Perl or PHP. Use built in functions and nested functions to achieve your desired result. In most cases, you will be able to extract all necessary records from all tables in one call to the database.

Table Joins

Table Joins are by far the most useful function on large and complex databases. They allow you to select and retrieve records from multiple tables in one action. When selecting records from multiple tables, you must use a common denominator other wise many more records than you expected will be returned. There must a column name common to two or more tables. Let’s assume we have two tables with the following structure :

Table 1

employees

Columns

id
firstname
lastname
address

Table 2

salary

Columns

id
hourly
ssn

Note that the common column is the id column. Your where clause must contain a common column, otherwise more records than you expect will be returned. In the following select statement, each table is separated by a comma. We are selecting all columns (denoted by an asterisk *) where the id is identical in both tables.

SELECT * FROM employees, salary WHERE employees.id = salary.id &&
employees.firstname = ‘Grayson’

In the example above, column names are preceded by table names to avoid confusion. Strings (as opposed to integers) must be quoted. The id is an integer (a whole number) so it does not need to be quoted. The first name is a string, so it must be quoted. Note that the common column is the id. Without the id check (employees.id = salary.id), all records from both tables that contain the string ‘Grayson’ would be returned.

MySQL Tips and Functions

• Comparison operators
= Equals
< Less than
<= Less than or equal to > Greater than
>= Greater than or equal to
<> Not equal to
!= Not equal to
LIKE Compare strings

• Mathematical operators
( ) Use parentheses to force precedence
+ add
- subtract
* multiply
/ divide
% modulo

• Conditional operators
|| Logical “or”
| Bitwise “or”
OR Same as Logical “or”
&& Logical “and”
& Bitwise “and”
AND Same as Logical “and”

• Some Common Functions

CONCAT(str1,str2) Concatenates strings
DAYNAME(date) Returns the dayname for the given date
LAST_INSERT_ID( ) Returns the last record ID inserted
LENGTH(column) Returns the length of a string in characters
TRUNCATE(n,n) Returns stated number of decimal places
UNIX_TIMESTAMP( ) Returns the epoch

• Some Aggregate Functions
AVG(column) Average number from returned results
MAX(column) Returns the largest number from returned results
MIN(column) Returns the smallest number from returned results
SUM(column) Returns the sum of all returned results

Note : not all databases servers support all functions, many depend on the version your server is running. There are hundreds of functions that can be used alone or nested within one another. You really should buy a book for a complete reference.

Categories: MYSQL

Basic Oscommerce Tutorials

October 23, 2009 Leave a comment

1. Initial setup of your Store – Configuration

The whole admin section of osCommerce follows the following basic principle and is reasonably easy for anyone with a basic computer knowledge to administer.

To complete the following on your own installation of osCommerce
- highlight an item by clicking onto it, then click the edit button. Add or update the entry and finally click the update button.

Login to the Admin section of your osCommerce store

Then follow the Configuration link, then the link My Store – here you should update/change the following:

1. Store name – The name of the store.
2. Store owner – The company name that owns the store.
3. E-Mail Address – The “from” email address in the customer’s order email.
4. E-Mail From – Your store general email address.
5. Country – The country you are from.
6. Zone – The zone your store is located, necessary for taxes later.
7. Send Extra Order Emails To – The email address to send duplicate order details.

2. Logo – adding your own image

Use FTP to change the default logo

The main logo is located here:
www.your–domain.com/catalog/images/oscommerce.gif

The easiest method to replace this logo is to over-write the original with your own logo.

Other images that you may find useful to change are located in this folder:
www.your–domain.com/catalog/images/infobox/

3. Modify the colours – the cascading style sheet

Your sites style sheet

The style and colours of your store are controlled by a single css file:
www.your–domain.com/catalog/stylesheet.css

Changing the colours, font sizes, font colours, margins, etc. can be done very easily for the entire store using this file.

Detail on how to change css files can be found here: http://www.htmlhelp.com/reference/css/

4. Further customisation – PHP files

Altering default settings within PHP files

The two PHP files below that hold many default settings including the footer text and page title that appears on all your store pages, and the date format that will be used within your store.

www.your–domain.com/catalog/includes/languages/english.php
www.your–domain.com/catalog/includes/languages/english/index.php

Below is a guide to editing PHP files for those that do not have any previous experience of the PHP scripting language.

1.

Copy the following file from your server to your PC:
www.your–domain.com/catalog/includes/languages/english/index.php

(make a separate backup of the file to a safe location, in case you break the original!).
2.

Then open the file with notepad or your favourite text editor.
3.

On line 23 the following text appears:
define(‘TEXT_MAIN’, ‘Add your own text message here
- open /catalog/index.php and change the text for TEXT_MAIN.’);
4.

We are going to change the value assigned to TEXT_MAIN to My Store Name. Change the entry to:

define(‘TEXT_MAIN’, ‘My Store Name.’);

All we have done is change the text on the right. The main objective to note here is the text which we changed is on the right between the single quotes (‘), the constant TEXT_MAIN does not change.

You MUST ensure the text you add is within the single quotes. If you need to add a single quote within the text you are adding for example:
Seiretto’s Shop
You must add a slash to the text, so it is entered like this:
Seiretto\’s Shop

Double quotes can be added in the same way.

For more in-depth details see: http://uk.php.net/manual/en/function.define.php

Need to fully modify your hosting account? Then you should consider your own fully managed dedicated server.

5. TIP – How to find and alter text phrases on pages of your store

TIP: If you wish to change a text phrase displayed on any page of your store and need to find which PHP file holds the details:

1.

Copy the whole of your /catalog/*.* files and sub folders from your server to your own PC.
2.

Select and copy the text phrase which you wish to change from the page on your store.
3.

On you PC highlight the “\catalog\” folder and right click your mouse button and select search.
4.

In the input box named “Search for files or folders named:” enter:
*.php
In the input box named “Containing text:” paste in your:
text phrase

5.Then open and edit the PHP file as described here.

6. How to remove/modify unwanted languages

Login to the Admin section of your osCommerce store

Then follow the Localisation link, then the link Languages

- here you should update/change the Languages required.

OR, if you do not need the languages box to appear at all:

1. open the following file with notepad or your favourite text editor:

\includes\boxes\languages.php
2. and delete all contents (note that you are deleting the CONTENTS of the file, and not the file itself).

7. How to configure to receive copy orders via email

Login to the Admin section of your osCommerce store

Then follow the Configuration link,

- here you should update/change Send Extra Order Emails To as required.

Best joomla tutorials

October 23, 2009 Leave a comment

This guide is an in-depth tutorial to the information a Joomla site displays. It details how to plan and organize the information and user experience for the site. It also explains the hierarchy structure currently used in Joomla, sections and categories and how information can be content items, components or modules.

In This Guide

* How are web pages generated by Joomla?
* What different ways can I present content items?
* How can I organize my content?
* How do components and modules present information?

Planning Your Content

Sections and Categories, Static items, Blogs and Tables

One of the hardest parts of Joomla for those new to it to figure out is how content is organized. The relationship between sections, categories, blogs and tables can be very confusing.

To get a better idea of how a Joomla site can be organized, letÙs make a sitemap for an imaginary site. This is a standard planning tool used by web designers and is critical for a Joomla web site. ItÙs usually shown as a tree diagram showing all the pages in the site. Here is our example.

Example Site Map

Figure 4-1 A Website Sitemap

In this sitemap, each web page is represented by a box, the lines are links within the site. A sitemap represents viewer path through a site rather than content organization. It is still a useful planning tool for organizing the site however. Here there are seven pages, from an organizational point of view, it seems like there are four main areas of the site:

* About Us
* Widgets
* Contact Us
* Widget Blog

The first step in trying to understand how Joomla structures its content is to realize there are no pages!

OK, so what does that mean?

I talked about the idea of “placeholders” for the content in a CMS like Joomla. Remember, the content is stored in the database and needs to be placed onto the pages by Joomla. The CMS has spaces on its pages to place content and needs to know what content it should put there. Joomla only know what content should be used once you click on a link. Once the viewer has done this, Joomla now knows what page to generate, gets the content, and puts it into place.

Consider a very different example, a magazine. You turn to the index, look something up, get the page number and turn to that page. For that page to be filled with content, the magazine author/designer needed to have chosen the content and arranged it as they wanted on that page. So you turn to it and you see the content. This seems a daft example but it illustrates very well how pages are generated in a CMS. On a Joomla site, you click on a link (the magazine index) and then the content is generated and arranged on the page. So in the magazine case the pages exist before you go to it, but on a Joomla web site, the page only exists once you visit it. Strange but true.

The Least You Need to Know

Joomla generates a page the instant you go to visit it.

There are 4 main ways that Joomla generates content:

* Static content
* Dynamic content (organized in sections and categories)
* Components
* Modules

Note that these are not separate pages, in some cases itÙs possible to have more than one type on the same page.
Static Content

In a static site, this very simple sitemap would be 7 simple pages. The simplest ways of creating a site with Joomla is with static content, itÙs much easier to understand how a Joomla site is driven. Static content is just that, a single static content item in the database will correspond to a single page of content on your website; nice and easy.

The Least You Need to Know

A single static content item will be a single page on your Joomla site

LetÙs say we have a simple website of three pages, a “Home” page, an “About Us” page and a “Services” page.

Small Site Map Example

In the Content menu is the Static Content Manager. We have two static content items we have created, “About Us” and “Services”. These are created simply clicking the new button. You then get an editor appear and can fill in the information you want (weÙÙ look more at adding content later)

Static Item Content Manager

As we just discussed, the hardest things for users to realize about Joomla is that content does not exist by itself on the pages of their website, only in the database. It is only shown on the website when it is linked to in a menu, that is, itÙs the menus that determine the content of a Joomla site, not the content items. Sure, they will be there in the database, but they will only appear once we link to them in a menu somewhere. A consequence of this is that you have to create the content first and then the links to it.

This is true for all content that is in the “main body” of your pages, they must have a link to them to cause them to appear on the site. Just to increase the confusion, they must also be “published” in the content item manager. You can see that our two items above are published. LetÙs create a small menu to point to these two content items.

The Least You Need To Know

Menus determine both what will be on a page and how it will be laid out

Tip
An advanced menu technique is possible as the menu that causes the content item to be shown on a page does not need to be published or visible itself. This allows the creation of what I like to call a “landing page menu”. I can create a menu that is not itself published, that links to various other pages. I can then use these in various situations without having to link to them off my site. Maybe I want a special page that offers one of my products at a discount and give the URL in an offline newspaper ad, or a landing page for my Google AdWords campaign. To find these URLÙs, just look at the URL line in the Menu item. This technique is discussed more in the Tips and Tricks Appendix.

Now letÙs head over to the Menu Manager. We create a new menu clicking the New button.

Menu Module created Dialog

Figure 4-3 The module created when you make a menu

Note as we create the menu it tells us a “mod_mainmenu” module was created. Take note of that, we will be coming back to it later. “mod_” is just Joomla shorthand for some type of module and “mainmenu” is a type of module that outputs a menu as links.

Now we have our menu, we need to create the links. You can do this one of two ways.

1. Creating Menu Links from the Menu Manager

Open the menu you created in the menu manager (select the menu you created from the “Menu” option in the main menu).

Finding New menu
Figure 4-4 Finding the Menu Manager

Then click the “New” button in the top right. Note that the important buttons for any particular page in the Administrator site are always located here.

Clicking on the New button in the top right and you will get lots of choices. WeÙll be looking at these in later chapters, but for now, select “Link – Static Item”. Click the radio button and then click next.

Creating a New Link

Figure 4-5 Creating a new link

On the next screen, simply click on what static content item you want to point to and give the link a name. The name given will be the words that shows in the link. This is a critical point for SEO.

The link name does not have to be the same as the title of the static content item. Now, SEO wisdom tells us that the anchor text of a link, the actual words that are “underlined” are very important to achieve a good SERP with that key phrase. This makes our example good for showing what not to do. It would be pointless to try and achieve SERP for the phrase “about us”. If my website sold widgets, then it would make more sense to have a link that said “About our Widgets”, then at least I get Google points for having “widgets” in the link. For the most benefit, the title of the page I am linking to should also have the keyword phrase/anchor text in some version, perhaps “About Widget Inc, your quality supplier for Widgets”.

Now, while we are on link text and SEO, we should mention something else. When making a site care should be taken to make it as “usable” as possible. Usability experts tell us that the words in a link should match very closely the page we end up on. Steve Krug talks about this in his book, saying “if thereÙs a major discrepancy between the link name and the page name, my trust in the site will diminish”.

Taking both these factors into account, trying to place important keywords in the link text and making the link usable, is a balancing act. Often, doing better at one means worse in the other. DonÙt think you can dismiss usability, itÙs no good having good traffic if they all leave your site out of frustration. Needless to say, its work putting some careful thought into what you link text will be. Fortunately, its easy to change later, you just go and edit the menu item.

The Least You Need to Know

You can create links to a content item, but the content needs to exist first
The names of a link (anchor text) needs to be chosen very carefully

Back to static items.

2. Creating Menu Links from the Content Item

We mentioned another way of creating menu links, and itÙs probably an easier one. As you create a content item, there are 5 panels/tabs on the right hand side: Publishing, Images, Parameters, Meta Info and Link to Menu.

Note:
The content item must be saved before these tabs appear. Click “Apply” rather than “Save” and then they will be loaded.

Creating a new static content item

Figure 4-6 Creating a New Static Item

Creating the menu link is as easy as selecting the menu you want the link to appear on, selecting the type (not shown here as this is a static content item) and the “Link to Menu” button. Note, however, the menu must exist already before you can use this method.

So, we now have a site with a couple of pages, a menu that links to two static content items to show the on the website.

On to the last page on our site, the home page. Now we start getting to some of the aspects of Joomla that are more difficult to understand. The default set up for Joomla installation is that the home page is not a static page or a dynamic section/category; itÙs actually a special component.

The Least You Need to Know

You can create a menu link as you create a content item, you have to save the item first so you can see the menu options.
Component Content

The Front Page Component

We saw when we were selecting what type of link to have that that a menu link can link to a component. The default Joomla installation has a number of pages that are actually components: the contact us page, the search page, the news feeds page and lastly the front page component. None of these really have content items of their own, but pull their content from various places, either within the Joomla site database (contacts) or even other sites (RSS newsfeeds). Basically a component is a mini application that presents data in the main body of a Joomla site in some fashion. A good example of a component is a forum. The content presented is highly specialized and different from the rest of the site.

In almost every case (except this one) all components installed are in the Components menu. The Frontpage component is unique in Joomla in that it is not managed from anything in the Components menu, but rather in the Frontpage Manager in the Content menu. Quite simply the Frontpage component allows the publishing of any content item in a Joomla siteÙs database on the front/home page regardless of where it appears on the site.

The home page of your site doesnÙt have to be controlled by the Frontpage manager. Sometimes more control over its layout is needed, or some other requirement. The first item in the main menu will be the home page of your site. In the default Joomla installation this is set to be the Frontpage manager, but it could just as easily be a static content item, a table, or another component. Just remember, whatever is first in the list will be your front page or home page. One thing you need to be careful of is some issues with item ID with this relationship. For more information read this thread on the Official forum.joomla.org/index.php/topic,4259.0.html.

The Least You Need to Know

Components are mini-applications that present content in the main body is a special way
The home page of a Joomla site is a component. It allows you to pull content from anywhere in your site for the home page

A quick look at the Content Items Manager and you will see a column that controls if an item appears on the front page. You can simply click on these crosses and check marks to publish/unpublish items onto the front page. You can also change this setting in the publishing tab in the actual content item itself.

The Content Items Manager

This is a good example of a page that “does not exist”. What we actually mean by this is that the content is dynamically generated the instant you view the page. In the case of this dynamic page, the content is taken from other database locations to populate the home page. This concept of dynamically generated content is one of the main differences between CMS sites and static ones. You canÙt change a static page unless you go in and change (X)HTML in a file somewhere. In a dynamic CMS you can change content with a simple click of your mouse.

In the example we are using, a site of just 3 pages illustrates the important difference between static content items and dynamic content. In this site our home page would be empty. So far we have only 2 content items and they are both static. A static item cannot be “pulled” into other pages like a general content item. It has a 1 to 1 item to page correspondence. General content items however can appear on several pages.

Static and dynamic content

It is not a complete free for all in how you insert content into a page. You are limited by how you can manipulate the hierarchical content structure that Joomla uses to organize its content; sections and categories

The other components in the default installation of Joomla are:
Name Description
Banners Manages advertising banners
Contacts Manages contacts
Mass Mail Sends out email to all users
News Feeds Manages newsfeeds from other sites
Polls Manages dynamic voting polls
Syndicate Manages RSS syndication
Web Links Manages simple web link directory
Dynamic Content
How Joomla Organizes Content: Sections and Categories

LetÙs go back to the example we started with, our 7 page site. Now that we have a better idea of what dynamic content is we can think not in terms of pages but in terms of content items.

We know that two of these pages will be special components, the home page and the contact us page. A component is basically a special page that does something unusual to the content in presenting it. That leaves us with 5 other pages. We can see that there are actually 7 content items here:

1. About Us
2. Services Description
3. Widget Blog Description
4. TodayÙs blog
5. YesterdayÙs blog
6. Green Widgets
7. Blue Widgets

Joomla gives us two organizational structures, first sections, and then inside that, categories.

Tip
In the Joomla roadmap are plans to change the hierarchical structure to be infinite categories.

At first glance, our structure might seem obvious, leaving out the two components, we have three sections:

* About Us
* Services
* Widget blog

Now, things start getting complicated.

You canÙt put content items in a section, they must go in a category. This means that each section needs at least one category.

A frequently used analogy is a filing cabinet. In the cabinet you have drop down folders, inside them you have manila folders and inside those sheets of paper with content on them.

How Joomla stores its content

The filing cabinet is the website, the dropdown folders are the sections, the manila folders are the categories and the paper is the content. To continue the example, static content would be loose sheets of paper in a stack at the bottom of the cabinet. ThatÙs why bigger sites need to use the section/category model, it organizes the information. I am not sure what a component would be, maybe a rolodex on top of the cabinet.

So one way to organize our content might be like this:
Sections About Us Services Widget Blog

Categories

About Us Blue Widgets
Green Widgets Widget Blog

The services categories work fine and make sense, the other two seem to duplicate the content level. This is because the content hierarchy for that area is only one “level” deep. You end up with a redundant level.

There are two solutions to this.

First and perhaps the easiest is to make all single level items static content. We have already seen that this is easy to set up. The down side is that the site can quickly become difficult to maintain. I have found this to happen with many more than 10-15 static items, mainly because Joomla provides no organization for them, they are all lumped into one group.

The second solution is to be more creative with our sections/categories. For example, we could have just a single section, letÙs call it “AllContent”. Then we have all the sections inside it:

Sections

AllContent
Categories About Us
Blue Widgets
Green Widgets
Widget Blog

Or we might have something in between. This problem often occurs with smaller sites with not too much content. In those instances you have to get creative.

In our example it might be good to use both. A single static item for About Us and then two sections for Services and the blog. The Widget Blog is a good candidate for its own category and section because they tend to have lots of entries. Even though there is a redundant layer of structure, it will easier to keep organized in the site.

The Least You Need to Know
Content items must be in a category which must be in a section. This can lead to a redundant organizational level for small sites
There are many ways to organize the same set of content in a Joomla site

Module Content

The last type of content is a module. The content presented in a module is very different to static or dynamic content, or components. In all three of the first types, the content is presented in the main body of the web pages. The template designer actually has to give a snippet of code to set the “placeholder”. Modules however can be anywhere on page. Most commonly you will find them around the edges; the top, sides and bottom.

Having said that modules are a type of content, that is not strictly true. Some types of module take in data rather than output data. An example of this is the login module. The default modules on a default Joomla installation are:
Name Description
Banner Shows banners from banner component
Menu Presents links of a menu
Login Form Shows a form to log in or create account
Syndicate Shows RSS feed links that viewers can use to syndicate to the home page
Statistics Shows various site stats
Template Chooser Allows user to change template of site on the fly
Archive This module shows a list of the calendar months, which contain Archived items.
Sections Shows a list of all Sections configured in your database
Related Items Shows links of content items that have similar keywords
Wrapper Presents another URL inside an iframe (a page within a page)
Polls Shows polls from the poll component
WhoÙs Online Shows number of viewers currently on the site
Random Image Shows a random image
Newsflash Shows a random content item from a chosen category
Latest News Shows link list to most recently published content items
Popular Shows link list of most popular content items (by page view)
Search Shows a search box
User A special module that is created by the administrator. It can contain either RSS feeds or any sort of html.

We wonÙt go into too much detail about how modules work. There are a number of settings/parameters related to their function in the index.php, the template file that controls all the presentation on the site. A more detailed developers guide to dev.joomla.org/content/view/1136/79/

Guide Summary

* Joomla is a dynamic content management system. Web pages are generated by the server software at the very instant you visit them. One implication of this is that in Joomla, the menus actually determine the content and layout of a web page.
* Joomla has two main types of content, static and dynamic. Static content has a 1 to 1 relationship between content items and web pages. This is not true for dynamic content, a single page can hold many items and vice versa.
* Joomla has a 3 level content organizational hierarchy. Content items are held in Categories which are held in Sections. In the current versions of Joomla, all dynamic content must follow this organization. This can sometimes lead to a redundant level for small sites.
* Content is also presented by components and modules. Components are mini applications that run inside Joomla, like a forum. Modules even smaller functions relating to the site, for example a log in form or a poll. Components are always presented in the mainbody, modules are usually output in side columns or header/footers.

Categories: JOOMLA

50 WordPress Tutorials

October 23, 2009 Leave a comment

WordPress Basics

1. Unraveling the Secrets of the comments.php File

Nettuts+ author Gilles Maes has written an in-depth overview of the comments.php file and how to make the most of the template.

2. How to Become a WordPress Developer

iThemes has a tutorial on how to become a WordPress developer. The article covers development tools, best plugins, suggestions for getting clients, and more.

3. Multiple WordPress Installations Using a Single Database

Streamline your WordPress set-up by installing multiple instances of WordPress on the same database.

Theme Tutorials

4. How to Create a WordPress Theme from Scratch

Nettuts+ author Sam Parkinson gives a thorough overview of how to make your own custom theme from scratch, complete with source code.

5. So You Want to Create WordPress Themes, Huh?

A lengthy and thorough series of tutorials covering nearly every aspect of WordPress theme development. A must-read for beginners.

6. WordPress for Designers: Video Series

Drew Douglass will teach us, using easy to understand screencasts, exactly how to design for WordPress.

7. WordPress Theme Hacks

A collection of simple WordPress hacks that you’ll find yourself reusing all the time when working with themes.

8. Designing for WordPress Screencast

CSSTricks has an excellent 3-step screencast that starts with the basics of solid theme design (step 2 and step 3).

9. Turning a Web Template Into a WordPress Theme

Instead of using one of the many standard WordPress themes, you could convert a web template into a WordPress theme with this video tutorial.

10. WordPress CSS Guides

A slightly-dated but still useful guide on how to alter the CSS on default themes to create your own personalized theme.

11. How to Create a WordPress Theme in 5 Minutes

Bothack has a quick-n-dirty rundown on how to create your own WordPress theme in 5 minutes.

12. Mastering WordPress Theme Hacks and Techniques

Nuope has a 4-part series on Mastering CSS, one of which is how to master WordPress theme hacks.

13. Blog Posts in Different Columns

If you’re wanting a little more advanced look and feel to your blog, try setting the posts to display in different columns.

14. Adding Tabs to Your Theme’s Sidebar

Here’s a quick hack that adds tabs to your sidebar using Yahoo! Tab View.

15. Category Styling

This tutorial shows how to add messages in the theme for posts in a certain category using CSS.

16. Multiple Page Layouts in a Single Template

If you’re looking for a more diversified template for sub-pages in a template, check out this quick tutorial for mutiple page layouts in a single template.

17. Rounded Corner Tab Menus

Rubique has a quick tutorial on how to use CSS to make rounded corners for your WordPress menus.

18. Dynamic Classes or ID’s

Elliot Jay Stocks as a useful tutorial on how to apply a dynamic body class or ID to your templates, for styling purposes.

19. Formatting Images for Feed Readers

How to make sure your images are looking good in many of your blog follower’s favorite medium: the feed reader.

20. How to Highlight Author Comments in WordPress

Google blogger Matt Cutts offers some advice on how to style your author comments differently than the rest of the reader comments.

21. Customizing Widgets Using CSS

Widgets are a great way to quickly add information to your layout (namely the sidebar). Here’s a tutorial on how to style the widgets using CSS.

22. Using Sliding Doors with WordPress Navigation

The Sliding Doors technique is a great way to utilize CSS and background images to make tabbed navigation. WPHacks shows us how to utilize Sliding Doors to enhance WordPress navigation.

23. WordPress Categories in a Horizontal Drop-down Menu

How to use CSS and Javascript to make a horizontal drop-down menubar.

24. Separate Comments from Trackbacks

It’s a good idea to separate trackbacks from your comments.

25. Creating a Widget Ready Footer

There’s a trend for blogs to have footers that feature columns of extra information. Learn how to create a widget-ready WordPress footer.

26. Make a Featured Post Carousel

Many blogs use a featured post carousel to show recent posts or flagship content. Learn how to create this nifty feature with Nettuts+ author James Lao.

27. How to Lay Text Over Images

Add a little flair to your blog and add some text to your flagship images by only using WordPress custom fields.

28. The Date/Image Hack

Interesting tutorial on how to combine a combination of images, CSS and WordPress hooks in order to graphically display the date of the published post.

29. Dynamic Sticky Pages

Learn how to dynamically make posts stay on top longer in category and archive listings using multiple loops.

Plugins

30. Your First WP Plugin

Mark Jaquith has a short-and-sweet screencast on how to create your first WordPress plugin in under 5 minutes.

31. How to Write a Simple WordPress Plugin

A step-by-step guide to a simple and fun WordPress plugin.

32. Screencast on Writing a WordPress Plugins

If you’re rather see a visual demonstration of how to write a WordPress plugin, look no further than the Weblog Tools Collection screencast.

The Backend

33. Custom Write Panels in the WordPress Backend

Design blog WeFunction shows us how to create extra write panels for adding extra bits to the “Write” page of the admin area.

34. WordPress as a CMS

WordPress isn’t just a blogging tool, it can also be a CMS with the help of some plugins and theme retooling.

35. Exporting WordPress Data

Learn how to import and export your WordPress posts and comments with this handy screencast.

Miscellaneous

36. Embedding WordPress into OS Commerce

OS Commerce is a popular open source ecommerce shopping script that many web developers use to sell goods. Here’s a tutorial on how to embed a WordPress blog into an OS Commerce installation.

37. Creating An Automatic Sitemap

Sitemaps help users navigate the site, as well as allow search engines to have quick access to all of your blog’s pages. Here’s a tutorial on how to create an automatic sitemap for your WordPress installation.

38. Build a Dynamic Design Portfolio

A terrific guide on how to utilize the query_posts tag to create a design portfolio with WordPress.

39. Create a User Contributed Link Feed w/ WordPress Comments

If you’re wanting to add a Nettuts+ style link feed, Collis has an excellent tutorial on how to utilize WordPress comments to create the feed.

40. A WordPress-Powered Membership Directory

WPDesigner shows us how to create a membership directory using a standard installation of WordPress and some customization.

41. Remove Categories in the WordPress Loop

Sometimes excluding certain posts in categories from showing in the WordPress loop is important. Here’s a quick tutorial with sample code on how to exclude certain categories in your templates.

42. Add a Twitter Field to your Form

How to install the twitip-id plugin to include a field for commenters to leave their Twitter ID.

43. Enabling HTTPS for WordPress.com Blogs Screencast

The WordPress team has put together a how-to video on enabling HTTPS on WordPress.com blogs.

44. How to Add Photo Captions

Good photo captions aren’t that something that WordPress themes usually come with out of the box. This screencast shows how to correctly add photo captions into your posts.

45. Make a Random Post Button

Adding a random post button is only a SQL query and PHP snippet away.

46. RSS-Only Posts

This tutorial shows you how to create posts that only appear in RSS feeds, in hopes to improve RSS subscriber counts.

47. WordPress SEO

Yaost has a lengthy tutorial on how to squeeze the most SEO out of your WordPress blog.

48. Learn How to Make Your Blog Accessible

Most blogs don’t conform to WAI/WCAG standards in terms of accessibility. Learn how to meet these standards with Bruce Lawson’s accessibility hacks.

49. Definitive Guide to Semantic Web Markup for Blogs

Although not strictly a WordPress tutorial, Chris Pearson’s guide to semantic web markup for blogs is a must-read for anyone wanting to maximize their results in search engines.

50. Digg-proof Your WordPress

Learn how to configure MySQL, Apache and other things to keep your site humming when it lands on the front page of Digg.

Categories: WORDPRESS Tags: , ,

PHP Basic tutorials

October 23, 2009 1 comment

PHP is a powerful scripting language that fits gracefully into HTML and puts the tools for creating dynamic websites in the hands of the people — even people like me who were too lazy to learn Perl scripting and other complicated backend hoodoo.

This tutorial is for the person who understands HTML but doesn’t know much about PHP. One of PHP’s greatest attributes is that it’s a freely distributed open-source language, so there’s all kinds of excellent reference material about it out there, which means that once you understand the basics, it’s easy to find the materials that you need to push your skills.

This tutorial, originally submitted by Webmonkey contributor Tim Ziegler, is a wiki. Please help us keep it up to date. If you have extra advice, log in and add it.

Introduction

What Is PHP?

So, what is this whole PHP business all about?

PHP is a program that gets installed on top of your web server software. It works with versions of Apache (Tutorial:Apache for Beginners), Microsoft IIS and other server software packages.

You use PHP by inserting PHP code inside the HTML that makes up your website. When a client (anybody on the web) visits a web page that contains this code, your server executes it. That’s why you need to install your own server in order to test PHP locally — the server is the brain here, not your browser. Users don’t need any special plug-ins or anything to see your PHP in action — it gets to the end user as regular old-fashioned HTML.

PHP is a scripting language, like HTML. That means that code does not need to be compiled before it gets used — it gets processed on the fly as necessary.

Before we dig in, you should know about a site called PHP.net. PHP is an open-source language, and PHP.net is its control center, with extensive reference material about the language and tips sent in by users across the globe. PHP.net has exceptional, deep information about the language, but it can be a little cryptic for the newcomer. We’ll look more closely at how to use PHP.net at the end of this tutorial.

So, what kinds of things can PHP do? Welllll … it can:

  • take info from web-based forms and use it in a million ways (store it in a database, create conditional pages depending on what the forms said, set cookies for later, send e-mail, write your mom on her birthday);
  • authenticate and track users;
  • run threaded discussions on your site;
  • serve different pages to people using different browsers or devices;
  • publish an entire website using just a single layout template (server-side includes-style);
  • serve XML pages.

But before we can get to the specific uses of PHP, we need to start with a quick preview of the building blocks of PHP, beginning with a sample script. This example script is titled “chickenman.php.” When called by a web browser, it would simply read, “I am the CHICKEN MAN!”

    <?php

    print ("I am the CHICKEN MAN");

    ?>

The ?php and tags start and end a PHP script, and your meat goes in the middle. Got that? Good! Now let’s walk through the basic rules you need to know to before you can write your first PHP script.

What you’ll need

Before we begin, you will need to install a server on your own machine in order to test your PHP scripts locally. You can install WampServer for Windows machines from http://www.wampserver.com/en/ In order to have a Localhost machine. If you’re using a Mac you can get MAMP from http://www.mamp.info.

If you have space on a web server which supports PHP, you can also test your PHP there, but this is kind of a pain because it means you’ll need to FTP your files or telnet in every time you want to change something.

Steps

The Basics

The code itself fits right inside a page’s HTML, and like HTML it is made up of plain ol’ text. So a page that displays the words “I am the CHICKEN MAN!” message would sit inside an HTML page named something.php, like this:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
<html>
 <head>
 <title> Chicken Man Example </title>
 </head>

 <body>

 <font color="red">My PHP code makes this page say:</font>

 <p>

 <?php

 print ("I am the CHICKEN MAN");

 ?>
 </p>

 </body>
 </html>

See how that works? The HTML is rendered as regular HTML, but everything inside the ?php and tags gets processed as PHP.

Basic Syntax

It’s time to write your own first PHP script. The basic rules of PHP are as follows:

Naming Files In order to get a PHP script working, the file it’s in or the file that it calls to do the heavy lifting must end in .php (earlier versions used the file extensions .php3 and .phtml). Like HTML, your files are saved as plain text.

Comments It’s important to get in the habit of leaving notes about your code with the comment tags so that months down the road you can make sense of what you were trying to make your script do. The way you set comments apart from your code (that you don’t want displayed or executed) is with either “//” at the beginning of each line, or surrounded by “/*” and “*/” if you want to comment out several lines:

<?php

// This will be ignored. Note to self:
// Pick up ice cream, cake, and balloons.

print ("I am the CHICKEN MAN");

/*
This, too, will be ignored.
Hey, and don't forget
the spanking machine!
*/

?>

Code Syntax

Start of Code Every piece of PHP code begins with “<?php” (or the abbreviated “<?” if your server is configured to handle that).

End of Code The way to signify that the PHP code is finished is by adding “?>” at the end.

Every Chunk With a few exceptions, each separate instruction that you write will end with a semicolon.

Parentheses The typical function looks like this …

print ( );

… where “print” is the function and the stuff that the function works on sits inside the parentheses, with a semicolon to finish it off. (Just to confuse you, “print” is the exception that also works without parentheses.) By the way, echo () is the same as print ().

Much like HTML, the actual formatting of your PHP code (where you put spaces, line breaks, etc.) will not affect the outcome except those parts of the code that tell a web browser how to display your page. So this piece of code …

<?php

    print ("I am the CHICKEN MAN");

    ?>

... is effectively identical to:

    <?php print ("I am the CHICKEN MAN"); ?>

Like more complicated HTML, it behooves you to use white space and tabs in your code to make the code more understandable.

Ready to write your first script? Let’s go.

Your First Script

OK, so write your first script already! Copy the following script, but put whatever you want inside the quotation marks. “Print” here means print to the screen of a web browser when you open the file:

<html>
<body>

  <?php

  print ("I am the CHICKEN MAN");

  ?>

</body>
</html>

Save the file with any name that has no spaces and ends in .php, and if you’ve installed a server on your own machine, you need to save the script somewhere inside the server’s root folder (on Windows this is typically in the “wwwroot” directory inside the “inetpub” directory on your C: drive).

The next step is to open the file in your browser. Since you need the server to run your PHP code, you have to open the file through a URL that finds the correct file through your web server. On Windows, your computer name is your root URL. My computer name is “rocketboy,” so to see the contents of my root directory, I type “http://rocketboy” into the Web browser and voila! I see the contents of my root folder. To open the file “chickenman.php” in a directory called “tests” inside the root directory, I’d type “http://rocketboy/tests/chickenman.php” and see my example.

If you’re testing on a PHP-able web server, FTP your files anywhere on your server and they should work when you open them through the URL.

Go on now and get your first script working. Then come back and we’ll have some fun. Together. (If you can’t get your first script working, look at our First Script Troubleshooting Guide.)

Error Messages

Fun, eh? Fun if it worked. If not — if you had an error in your script — you probably got an error message that looked something like this:

Parse error:
parse error in C:\Inetpub\wwwroot\webmonkey_article\test9.php
on line 12

Error messages can be very useful and you’re bound to run into lots of them. You’ll get a message like this for every line in your script that has an error. For our purposes, all we really need to know is that there is something wrong with our code in line 12 of the document “test9.php,” so let’s look at that line and see if we can figure it out (good text editors like BBEdit have a function that lets you jump to any particular line). I always start by looking to see if my basic syntax is correct: did I leave out the closing tag, a line’s semicolon, quotation marks?

A Few More Statements

Let’s continue by adding to your test code from the last page to show a couple useful tools.

In the same code that you wrote before, drop in a couple more statements. As you see, you can gang up more than one PHP function inside the same opening and closing tags. My comments in the code explain what each part does:

    <html>
    <body>

    This text right here (or any HTML I want to write)
    will show up just before the PHP code stuff.
    <p>

    <?php

    // first, this $PHP_SELF thang is
    // an environment variable that'll show the
    // path from your root folder to this
    // document itself, like /webmonkey_article/test3.php.
    // I put this in just for fun.
    // NOTE: This may only work if your server is Apache.

    print "$PHP_SELF";

    // next we have to "print" any
    // HTML code we want the browser
    // to follow to determine
    // the layout of the results page.
    // In this case, we're adding a <p> tag
    // the <p> tags could have been put
    // inside the same print statement as the
    // "I am the CHICKEN MAN" text.
    // between the $PHP_SELF text and the
    // next bunch of stuff.

    print ("<p>");

    print ("I am the CHICKEN MAN");

    print ("<p>");

    /* This next "phpinfo" business outputs a long page that
    tells you exactly how your version of PHP is configured.
    This can be useful when troubleshooting problems down
    the road */

    phpinfo();

    ?>
    </p>
    </body>
    </html>

NOTE: Phpinfo will output a long page of info about your version of PHP. You don’t need to understand what it all means, I just wanted to show you that it’s there if you ever need it.

Very Able Variables

So far, all we’ve done is have a PHP script print some text. Big whoop. Let’s get down and dirty now with variables. A variable is a container for holding one or more values. It is the means by which PHP stores information and passes it along between documents and functions and such. You may remember variables from algebra — in the equation “x + 2 = 8″, x is a variable with the value 6.

The reason why variables are so important to PHP is that the very notion of having dynamic web pages — pages which respond somehow to user input — relies on data being passed around between pages (or parts of a page). Variables are the main mechanism for transferring data like this.

I think the easiest way to explain how variables work in PHP is to show them in action. There are three basic things you can do with variables:

  1. Set them (give them one or more values);
  2. Re-set them if they were set before;
  3. Access them (read the value of a variable and then do something useful with it).

Variables in PHP start with a dollar sign (“$”). Below I am setting a variable, using it, then setting and using it again. The value that a variable holds can be changed any time at all.

1. <?php
2. $utterance = "I love you!";
3. print ("When I'm happy, I want to say $utterance");
4. print ("<p>");
5. $utterance = "I will smite you!";
6. print ("When I'm angry, I want to say $utterance");
7. ?>

Here’s what that page will look like:

PHP_Tutorial_utterance.gif

In line two I have created a variable that I decided to name “utterance.” All variables start with “$”, so my variable is written “$utterance” in the code. Here’s how that last code snippet breaks down line by line. Please note: the webserver does the PHP interpreting before sending the browser finished HTML code.

  • Line 1 tells the webserver: “Start PHP code here”.
  • Line 2 creates the variable $utterance and also sets it, giving it the initial value of “I love you!”.
  • Line 3 prints a phrase that draws on the variable $utterance.
  • Line 4 creates atag in HTML to put vertical space between the two utterances.
  • Line 5 RE-SETS the variable $utterance and gives it the value “I will smite you!”.
  • Line 6 prints a new phrase that draws on the new meaning of the variable $utterance.
  • Line 7 tells Mr. Webserver: PHP code ends here.

See how the variable $utterance is used as a sort of container that can hold different values? We just set and then called variables inside the same script, but the power of PHP is that you can set a variable in one place — say from a form that a user fills out — and then use that variable later.

The syntax of setting a variable is to:

  • define it with the = sign ($utterance = “I love you!”;);
  • use quotation marks if you’re defining it with a string of letters (“I love you!”; numbers don’t require quotes);
  • end each instruction with a semicolon.

Then you call it by refering to the variable name ($utterance in lines 3 and 6 — notice no quotation marks there).

Naming Variables

You can name a variable anything you want so long as it follows these rules:

  • it starts with a letter;
  • it is made up of letters, numbers, and the underscore character (that’s the _ character, as in “$baby_names”);
  • it isn’t used elsewhere (like “print”).

Warning: Variable names are case-sensitive, so $baby_names and $Baby_names are not the same. You also should try to make your names have some meaning so that you can still make sense of your code next year.

In the examples so far, we have set variables as chunks of text, which are known as “strings.” Variables can also hold the values of numbers and some other things as well (objects, arrays, booleans).

Final note: One thing that can be a little confusing when starting to use PHP is the use of quotation marks inside PHP functions. Use single or double quotes to set off strings (that is, chunks of text), as in:

    print ("I am the CHICKEN MAN");

This will print the text I am the CHICKEN MAN. If you want to display quotation marks as characters in the output of your PHP script, you must escape them with the “\” character, which tells PHP not to use the next character as part of the code. So to output the text “I am the CHICKEN MAN” (with quotation marks showing in the result) the code would look like:

    print (" \"I am the CHICKEN MAN\"" );

HTML Forms and PHP

In our examples so far, we have set variables and then used them all in the same code. This doesn’t make much sense because in those instances, we could have just hard-coded the values instead of using variables.

Let’s get some real mileage by creating HTML forms to gather user input, turning that input into variables, and then doing various things with the information that we just collected.

No sense in sitting around waiting – let’s go ahead and make a Web page that collects your favorite dirty word and displays it on another page that tells you what a pervert you are. All of this gives a page that looks a lot like this.

First, we make the form page, which is regular HTML with a form in it. I’m calling mine “badwords_form.html,” but call yours whatever you like. (If you want a good primer on HTML forms, read Jay’s How To Add HTML Forms to Your Site tutorial.)

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
<html>
 <head>
 <title>My Form</title>
 </head>
 <body> 

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

 My name is:
 <br> <input type="text" name="YourName"> 

 My favorite dirty word is:
 <br /><input type="text" name="FavoriteWord"> 

 <input type="submit" name="submit" value="That's Right!">
 </form>

 </body>
 </html>

This is a regular HTML form. The important pieces are as follows:

Line 7: the HTML that reads action="bad_words.php" tells the browser which PHP document will process the results of the form. That is to say, in a minute you’ll create a document called “bad_words.php” which will be the little engine that makes the result page happen. (We’ll get to the method=post part later on.)

Line 10: input type="text" determines that the form element which we want here is “text” or a text box (we could also have a radio button, check box, etc.); name="YourName" determines that whatever the user types into the text box will become a variable that we have called “YourName.” This is what ties together forms and variables – each form field can set a variable to be used however you want.

Line 13: here you have another text input that sets a variable called “FavoriteWord” which is the user’s favorite dirty word.

Line 16, 17: This code makes a submit button with the text “That’s Right!” and ends the form.

So this form will collect the unassuming user’s name and favorite bad word, but now what do we do with it? Let’s take the variables she set and echo them back in another context on another page.

On line 7 of the HTML above, we told the form to head on over to bad_words.php once the submit button was hit. This is what bad_words.php looks like:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
<html>
<head>
<title>Perv!</title>
</head>

<?php
// Capture the values posted to this php program from the text fields
// which were named 'YourName' and 'FavoriteWord' respectively

$YourName = $_REQUEST['YourName'] ;
$FavoriteWord = $_REQUEST['FavoriteWord'] ;
?>

<body bgcolor="#FFFFFF" text="#000000">
<p>

Hi <?php print $YourName; ?>

<p>

You like the word <b> <?php print $FavoriteWord; ?>!?!</b>

<p>You oughta be ashamed of yourself!

</body>

</html>

See how this form passed a variable along from the form page to the PHP file? You have not seen the last of this.

Get versus Post

So far, we’ve used the “Post” method of passing form data as opposed to the other method, “Get.” This is the part of the form code that reads form action="bad_words.php" method=post¢.

The difference between these two is that the “post” method transparently passes along all the information the page has gathered, whereas the “get” method will pass all that info along as part of the URL (in the form above, this would look like: http://rocketboy/webmonkey_article/bad_words.php?YourName=bob&FavoriteWord=crikey%21&submit=Enter+My+Data%21 – see how the info the user entered about his name and his favorite word get added to the URL?)

Arrays

One of your best tools now that you’ve mastered variables – you have, haven’t you? – are arrays.

Arrays give you the ability to store not just one value inside a variable, but a whole bunch of values in a single variable.

If I wanted to catalog all of the animals in my house, I could set each one as a regular variable. I’ve got two dogs, Phoebe and Ruby, and a squirrel that died in the attic last year, whom we’ll call Rotty. Setting each one as a variable looks like this:

$dog1 = "Phoebe";
$dog2 = "Ruby";
$squirrel1 = "Rotty";

But an array will let us store all these inside one single variable, which I’ll call $critters. Each element of the variable has its own “key” that is used to access that part of the array, which can either be a string of letters or numbers.

Let me explain the “key” concept another way: If we’re storing three different values inside one variable (like storing Phoebe, Ruby, and Rotty inside $critters), we need some way to be able to suck out any individual part of the array to use it. An array will automatically number each element that comprises it, so the key can be element 1, element 2, and element 3. Or, as we’ll see later on, we can name each part of the array with text. In this case I could make the keys “fat dog,” “skinny dog,” and “squirrel” and use those to identify each array member.

Let’s make a simple array and then use it. The easiest way to create an array is to use the array() function, which assigns a bunch of values to your array at once and looks like this:

    $critters = array ( "Phoebe", "Ruby", "Rotty" );

This stores all my animal names into one variable ($critters) in an array, and automatically assigns a numbered “key” to each element starting in order and giving the first element the number 0. So Phoebe is element [0], Ruby is [1], Rotty is [2], etc. I make up the name of the array myself (here it’s $critters).

You can now get at any of the array elements by referring to the variable followed by the element number in square brackets: $critters[0], for example. Here it is in action:

<?php

    print "$critters[2]";

    ?>

This will simply print the third element in the array, which is Rotty (don’t forget that array numbers start at 0, so $critters[2] is third after $critters[0] and $critters[1]).

There’s another way to set an array, or even to add to an existing array, by setting each element individually:

 $critters[] = "Phoebe";
    $critters[] = "Ruby";
    $critters[] = "Rotty";

This’ll have the same effect as using the array() function, giving the first element the key [0] and so on. But wait! I forgot about Opie the cat. Hmmm. Regardless of how we made the array in the first place, I can easily add Opie like this:

    $critters[] = "Opie";

PHP is smart enough to count the number of elements and give Opie the next available one, which in this case (after Phoebe, Ruby, and Rotty) is [3].

To recap this concept, I can set an array to include the animals in my house either this way:

    $critters[] = "Phoebe";
    $critters[] = "Ruby";
    $critters[] = "Rotty";
    $critters[] = "Opie";

Or this way:

    $critters = array ( "Phoebe", "Ruby", "Rotty", "Opie" );

Both will be indexed in the computer brain with the values:

    $critters[0] = "Phoebe";
    $critters[1] = "Ruby";
    $critters[2] = "Rotty";
    $critters[3] = "Opie";

And in both cases, you could get at any element in the array by describing its number …

 <?php

    print "$critters[3]";

    ?>

… which would print the string Opie to the window of your browser.

Arrays can be made to do all kinds of things, like being incremented by number, sorted in alphabetical order, printed by different types of categorization, and many more.

Associative Arrays

Ready to get more complicated? The associative array indexes the contained elements not by numbers, but by names that you determine. Inside the array() function, you set up pairs where you name the key and its value using the combo of the “=” and the “>”, like: key=>”value”. Here’s what it looks like in action:

  $PhoebeDog = array (
    		name=>"Phoebe",
    		description=>"fat dog",
    		color=>"grey and white",
    		age=>7
   				);

Here we’re telling the array to create the keys “name,” “description,” “color,” and “age”; and we give each of those keys a value (name is “Phoebe”, description is “fat dog,” and so on).

We can get at any part of the array through the “key” names that we set, for example:

    print $PhoebeDog[color];

will give us grey and white. We can also set each key individually, like so:

    $animals[name] = "Phoebe";
    $animals[description] = "fat dog";
    $animals[color] = "grey and white";
    $animals[age] = 7;

Finally, let’s make it hurt. We’re going to get some serious power out of this arrays business by creating a “multi-dimensional” array. A multi-dimensional array is an array (say the animals in my house) that is made up of other arrays (for each animal, an array that contains the critter’s name, color, description, and age).

We make multi-dimensional arrays by creating one array:

    $animals = array
            (
    			);

…and then we fill that array with an array of animals in which we’ve defined the keys, like this:

    $animals = array (
    		array ( name=>"Phoebe",
    			    type=>"dog",
    			    color=>"grey and white",
    			    age=>7 ),
    		array ( name=>"Ruby",
    			    type=>"dog",
    			    color=>"brown and white",
    			    age=>7 ),
    		array ( name=>"Rotty",
    			    type=>"squirrel",
    			    color=>"grey",
    			    age=>2 ),
    		array ( name=>"Opie",
    			    type=>"cat",
    			    color=>"grey tabby",
    			    age=>5 )
    					);

To use this now, we can get any part of the information contained in there by naming the overall array ($animals), naming the number of the sub-array that we want to find out about (Phoebe is [0], Ruby is [1], etc.) and then naming the key for the attribute we want to get at (name, type, color, or age).

To find out the age of the cat, we’d write:

print $animals[3][age];

Here’s what it all looks like together. This is all in one page, but remember that you can set arrays in one place (in code or in form fields from another page or in a database, say) and get at the info contained within from somewhere else. Here I’m putting it all together on one page so you can see it all at once.

<html>
<head>
<title>Pet Arrays</title>
</head>
<body>

<?php

$animals = array (
		array ( name => "Phoebe",
				type => "dog",
				color => "grey and white",
				age => 7 ),
		array ( name => "Ruby",
				type => "dog",
				color => "brown and white",
				age =>7 ),
		array ( name => "Rotty",
				type => "squirrel",
				color => "grey",
				age =>2 ),
		array ( name => "Opie",
				type => "cat",
				color => "grey tabby",
				age => 5 )
					);

print $animals[2]["type"];
print ("<br>");
print $animals[3]["color"];

?>	

</body></html>

What we’ve just done is create an array that includes a sub-array for each animal which contains detailed info about that critter; then we print a sentence that uses the type and ages of two of the animals.

Operators; If, Else, Elseif; Loops

The whole deal about making dynamic websites is that you want your web page to be as smart as possible — to have code sitting there that can make all sorts of decisions based on different kinds of user input, user conditions (what browser is Visitor X using?), or information that you set yourself. Examples of this could be:

  • After a user enters an email address, check that it has a valid form (whoever@wherever.com) and if not, serve a page that says, “hey pal, how about a VALID email address?”
  • Serve one set of HTML to .com domains and another to .gov domains (where you try not to use any big words that might confuse ‘em).
  • Know whether a customer at your online store is meeting a minimum dollar amount for an online credit card purchase.
  • And on and on and on – the possibilities are limitless.

If

The way to make your pages smart is to use If, Else, and Elseif statements along with Comparison and Logical Operators. The most important one of these is the

if

statement, which gives you the ability to code:

    If some condition is true, then do somesuch thing;
    If the condition is not true, then ignore it;

The syntax of this statement is as follows:

 if (condition) {

// code in here to execute if the condition is true

}

Here it is in action. First we set the variable

    <?php

    $FavoriteColor = "blue";

    if ($FavoriteColor == "blue") {

    print ("I like blue too!");

    }

    ?>

Please note that:

if ($FavoriteColor = "blue")

and

if ($FavoriteColor == "blue")

are not the same thing, the first will always be true as it sets $FavoriteColor to blue.

Else

Else builds on the if statement as if to say:

    If some condition is true, then do somesuch thing;
    ELSE, in case that first condition is NOT true, then do this other thing.

It works like this:

if (condition) {

// code in here to execute if the condition is true

} else {

// code in here to execute if the condition is not true

}

Here it is in motion:

<?php

$FavoriteColor = "yellow";

if ($FavoriteColor == "blue") {

print ("I like blue too!");

} else {

print ("You don't like blue?! Crazy fool!");

}

?>

What you see above is the typical format for writing statements like this. The key part is to see where the curly braces are so you don’t get confused as to which statement belongs to which piece of the code. Above, the first set of { and } belong to the “if,” the second { and } belong to the “else.”

Elseif

There’s one more sibling in the if, else family, and it’s called elseif. Where else is sort of a blanket control that make something happen as long as the if statement is not true, elseif makes something happen if a specific condition is met:

IF some condition is true, then do somesuch thing;
    ELSEIF some other specific condition is true, then do another thing;

It looks like this:

<?php

    $FavoriteColor = "green";

    if ($FavoriteColor == "blue") {

    print ("I like blue too!");

    } elseif ($FavoriteColor = green) {

    print ("MMMmmmmmmmmmm, green!");

    }

    ?>

You could even add an ELSE statement at the end in case FavoriteColor were neither blue nor green.

Comparison and Logical Operators

We’ve seen how the “=” sign works when we set variables in the scripts we’ve written so far (as in the code $FavoriteColor = "blue"; and $utterance = "I will smite you!"; ). The equal sign here is what we call the “assignment operator” and is the simplest operator we’ve got: $a = b means “the variable a is assigned the value b (for the moment).”

But you can squeeze a lot more juice out of your PHP using what are called “comparison operators,” “logical operators,” and “arithmetic operators.” Here’s what they are, in tables copied verbatim from PHP.net.

Comparison Operators

These give you the ability to compare whether elements are equal, identical, less than or greater than one another (with some other variations).

Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (PHP 4 only)
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (PHP 4 only)
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

Logical Operators

Here you can compare elements using comparisons and, or, and the like.

Example Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.

Aritmetic Operators

Just what it says – this is basic math.

Example Name Result
$a + $b Addition Sum of $a and $b.
$a – $b Subtraction Difference of $a and $b.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Quotient of $a and $b.
$a % $b Modulus Remainder of $a divided by $b.

Loops

Loops are really handy. They let you program your code to repeat itself (and also to figure out how many times to run through itself before it’s done). Loops have instructions to “keep running this piece of code over and over again until certain conditions are met.” You can use more than one kind of loop. Let’s look at the most basic kind, the “while” loop.

The while loop says,

while (something is true)

{

// do something that you specify

}

While loops are often used with incrementing and decrementing a variable that is an integer. What in the hell does that mean? It means that you can automatically have the script add (or subtract) a whole number (1, 2, 3, etc.) from part of a script each time it runs through, until the number reaches a maximum or minimum value that you’ve set.

So if you wanted a script to print the numbers from 1 to 10, you can tell it (this is English, not PHP here):

a. the variable $MyNumber = 1;

b. print $MyNumber;

c. add 1 to $MyNumber;

d. go to sep a. and run this script again with the new value of $MyNumber;

d. stop when $MyNumber reaches 11;

The syntax for incrementing and decrementing the value of a variable is:

$a++; adds 1 to the value of the variable $a each time through
$a–; subtracts 1 from the value of the variable $a each time through

So the code itself for printing the numbers 1 through 10 could look like this:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
<?php 

$MyNumber = 1;

while ($MyNumber <= 10)

{ 

print ("$MyNumber"); 

$MyNumber++; 

}

 ?>
  • line 1: start PHP code;
  • line 3: set variable $MyNumber to 1;
  • line 5: initiate “while” loop: while the variable $MyNumber is less than or equal to 10, execute what’s below; otherwise move on;
  • line 9: print the current value of $MyNumber;
  • line 11: add 1 to the value of $MyNumber;
  • line 15: end PHP code.

For these loops, you can use all the “operators” listed on the section above to be the conditions that must be met before the loop stops.

Other Loops

PHP has other kinds of loops, but they are beyond the scope of this tutorial. If you want to learn what they are and how to use them, follow these links to PHP.net:

Functions

If you’ve used HTML a lot, you know that it’s a pretty limited language that was designed back in the dark ages before we all knew what the Net was capable of.

PHP, however, is very flexible. Not only does PHP have a library of canned functions that’ll do everything from sorting stuff in alphabetical order to sending email, from connecting with databases to balancing your spaceship’s inertial sub-space dampers, but you can also create your very own functions to do all manner of things related to your website. The functions you create get executed exactly like those from the PHP library, but they’re your own. In the following section, I’ll show a glimpse of how you create your own functions and feel the power.

Functions you create are like little machines that do something for you. You construct them and then call them as needed.

You’ll remember that the very first thing we learned to do was a simple “print” statement, which followed the form:

    <?php

    print ("whatever it is I want to show up on-screen");

    ?>

Functions that you create are built upon a similar form, but take it farther:

<?php

function MyFunction ()

{

statements that make up the function;

}

?>

So you start a function with the words function WhatYouNameIt(), with the words WhatYouNameIt() being anything you choose (no spaces).

Then you define the rules of the function inside the following curly brackets (that’s { and } on lines 5 and 9). Don’t you just love the words “curly brackets?”

Let’s walk through the making of a couple functions. Functions come in two flavors, those that require “arguments” and those that don’t. An “argument” is a variable that comes from outside the function, but which the function needs in order to run.

Let’s first look at one that doesn’t require arguments:

<?php

function ChickenMan()

{

print "<b>I am the CHICKEN MAN!</b>";

}

ChickenMan();

?>

line 1: start PHP;
line 3: create function ChickenMan;
line 5: start definition of function ChickenMan;
line 7: definition of ChickenMan is to print “I am the CHICKEN MAN!” inside and tags;
line 9: end definition of ChickenMan;
line 11: call function ChickenMan (meaning “do the thing that we defined the function to do”);
line 13: close PHP;

Any place in this web page that you put “ChickenMan();” inside the <?php and ?> tags, it’ll print your little statement. See how this saves you time if you want to print this string a bunch of times in different places?

Now let’s get a little more complicated and create a function that does take arguments. Say I’m a loan shark and I’m going to loan you the money to buy that personal hovercraft you’ve been lusting after. I’ll lend you however much you need, but you have to pay me 14 percent interest per week or I break your legs.

I’ll create a function called InterestPayment which calculates your weekly payments (until you pay off the whole loan amount in one lump sum).

First we’ll create a form page where the user enters how much of a loan he or she wants. The user enters the hovercraft’s sticker price, and that number gets passed along from the form as a variable called font size="2">$Cost. (For the HTML behind this, go here.)

Next, our function will take the amount that the user enters into the variable font size="2">$Cost and spit back 14 percent of that amount, which is how much the hapless borrower owes every week. This will happen in the PHP page titled “loanshark.php” that the form page points to (it points with this code: <form action=”loanshark.php” method=post> ). Here’s what the function will look like:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
<html>
 <head>
 <title>Loans</title>
 </head> 

 <body> 

 <?php 

 $interest_rate = .14; 

 function YouOweMe($cost, $interest_rate) { 

 $weekly_payment = ($cost*$interest_rate); 

 print "You better pay me \$$weekly_payment every week, or else!"; 

 } 

<font color="#000000">YouOweMe($cost, $interest_rate); 

 ?> 

 </body>
 </html>

Here’s the line-by-line breakdown.

line 8: start php;
line 10: set variable called $interest_rate to 14%;
line 12: create function YouOweMe that relates to the variables $cost and $interest_rate;
line 14: create variable $weekly_payment, the value of which is the cost times the interest rate;
line 16: print to screen a sentence that uses the value of the $weekly_payment variable;
line 20: engage the function YouOweMe, which (because of the function defined beforehand) simply prints the sentence You better pay me [14% of the amount the user entered on the form page] every week, or else!

Notice on line 16 that we want the code to actually print out a dollar sign before the weekly payment. We escape that character with a \ to make sure the PHP engine doesn’t think we’re naming a variable there. Then we just happen to name a variable right afterwards ($WeeklyPayment), so the two together look like font size="2">\$$WeeklyPayment.

Some Final Thoughts

If it got a little brutal back there trying to make sense of my functions, don’t worry — you’ll probably get used to squinting through other people’s code once you get going. That’s because somebody has probably written code for whatever you need to do already, and is probably happy to share it with you. Making sense of it all gets easier and easier the more you use this stuff. And since PHP is an open-source language (meaning the source code is shared openly instead of being hoarded by an evil corporation), the language is surrounded by a sense of cooperation among its users, many of whom will help you if they can.

Categories: PHP Tags: , ,
Follow

Get every new post delivered to your Inbox.