Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.

Topics - builder

Pages: [1]
1
Website Announcements / Missing Messages *** EXPIRED ***
« on: July 02, 2004, 01:12:57 AM »
We seem to have lost a lot of messages recently. We had about 10,000 and are running very low. Forums were set to prune older messages, but that was set to nearly a year, so I think there are more missing than that. I will look into it, but unsure whether I can restore most of them.

Steve

2
Website Announcements / One track mind
« on: March 31, 2004, 12:30:34 AM »
This is just to let you know that I am still here and appreciate the members of this forum keeping things running. In the last few months, just as I was about to make some changes on this site, three financially essential and large projects came my way. I had to relearn Perl for the largest. I need mental isolation to do my work and was afraid of getting too involved in the forums.  I hope this provides some explantation, and if someone needs it, my apologies for being absent without a notice. I won't make any promises, but as soon as I can, I will continue development of the site from where I left off last year.

Steve
(builder, onwer phphelp)

3
Posting Guidelines

  • Use common sense - Just because it isn't explicitly stated as one of the rules below doesn't mean it's OK. Use common sense and good Netiquette when posting, replying and browsing these forums.  Do not take a demanding tone in the forums. As my grandmother said, you will catch more flies with honey than vinegar. A suggestion from genealogy: you will get much more help if you do your homework before asking a question. Do not ask people to do your work for you. Don't be too general in your questions. Make your titles specific. Do not just post "newbie needs help." Asking good questions is an art and a learned habit, do not be shy to learn how to ask good questions. It took me a while to learn. Lurk on the forums before posting. Netiquette: http://www.albion.com/netiquette/corerules.html
  • DO NOT CONTACT COMMUNITY HELPERS BY EMAIL OR PRIVATE MESSAGE WITH TECHNICAL PROBLEMS In the past, members have received a large amount of personal messages asking for help with various technical problems. Help is provided in the forums. It cannot be stressed strongly enough.
  • Private Messages and Email Please post your questions in forums instead of sending private messages to the administrators or moderators of the discussions. Doing so will enable the whole group to work on your problem. No matter how knowledgeable an individual is, inevitably people have different points of view and will offer different solutions. It only benefits you and the community when questions are answered in the public forums for all to read. As with all rules they can and will be enforced, so from now on however important your question is please DO NOT private message the administrator or any other users unless they have personally requested that action.
  • Read articles in the relevant section on the main site - Start by looking for and reading articles in relevant topics in our collection of articles in addition to the forums. Chances are answers to many of your questions will be there. By doing the prerequisite reading and learning, your questions and comments will be both more answerable and more interesting to others when you do begin posting.
  • Read the PHP Manual Be sure to visit the official PHP website ( http://www.php.net ) and read the documentation (they offer an interactive version of the PHP Manual including reader comments). You will be surprised how many questions can be so easily answered if initiative is taken and posters read the manual.
  • Take advantage of the online PHP Manual
    Consult the Online Interactive PHP Manual available at (http://www.php.net/manual). You will find it contains many helpful annotations covering quirks, bugs and commonly asked questions. If you do not understand how the manual's advice applies to your problem, then please state what you do not understand and carefully define your problem.
  • Download the PHP Manual Download the official PHP documentation (PHP Manual) from the php.net website and install it onto your local computer hard drive for reference.
  • Do your homework firstOnce you have exhausted the PHP Manual (http://www.php.net) and learned the basic concepts of PHP programming, you can research more effectively on the site or post more clearly defined questions and get lots of helpful answers. The community members are a helpful bunch, by and large.
  • A problem defined is a problem solved. So please clearly state what you are tying to accomplish, the goals of your project, before posting. Please state your problem in clear, plain language. Community members are much more likely to answer if you carefully define and explain what it is you want to achieve before posting a question.
  • Use Clear Language Avoid any defects of spelling or grammar that would interfere with understanding your question. Do not type in all lower or upper case. Avoid substituting online slang or abbreviations for real words. You do not have to write perfect English or construct sentences befitting a an English teacher, but make writing understandable. Do not assume everyone is an expert with all programming technologies, avoid excessive technical jargon.
  • "Bumping" Message Threads Please try to limit "bumping" of threads unless they are fairly old, dropping out off the first page of replies, and of interest to the general community. If you feel a thread like that needs bumping, please suggest in a private message to one of the moderators that we make it 'sticky' instead.
  • Private Messages and Email Please post your questions in forums instead of sending private messages to the administrators or moderators of the discussions. Doing so will enable the whole group to work on your problem. No matter how knowledgeable an individual is, inevitably people have different points of view and will offer different solutions. It only benefits you and the community when questions are answered in the public forums for all to read.

How to Ask for Help

Here are a four steps to take when posting a technical problem:

  • Make sure you check http://www.php.net and read the documentation (they offer an interactive manual with reader comments), you'll be surprised how many questions can be so easily answered if initiative is taken and posters read the manual.
  • Please do not post "Can you Make This" enquiries. Most of us here will help with existing problems that you have come across and will not create whole programs for you. You will receive help quicker if you show that you have gone to some effort toward a solution.
  • Always provide as much background information as possible: Operating System : *nix, win etc etc; version of PHP (not necessary, but quite helpful for us)
  • If you are posting an error, please let us know:
    • What the error message is.   
    • What line of code is causing the error
    • Be sure to surround the code you post with the BBCode "Code" tags. A button for this is provided by a toolbar at the top of the "POSTING" page.
    • Please read the php debugging tutorial as well.

If you follow these four rules, you'll find that you will get a far more efficient and worthwhile answer in a quicker time span.

Help Installing Third-Party Applications

This forum does not offer support for the usage of pre-made scripts. There are far too many applications of varying types available for users of this forum to be able to answer questions or provide support. You will have to refer to the original developers support forum to find a solution.

If your application is generating a specific error or you can narrow the problem down to a certain code segment, we may be able to give you a general answer to that specific PHP problem. We have no ability to help if  you just say "Its not working, help me."

Please seek help in the application's support group first, wait for answers before asking somewhere else and try contacting the developers or authors. Be sure to check your configuration is correct and that the version of PHP you are running is compatible with the application or script.

Be sure to ask your hosting provider's support team about the version of PHP or any upgrades and configuration details, versions and configuration of support applications such as MySQL, the operating system (have their been any upgrades or switches to another flavor of Unix?), are appropriate libraries installed with the operating system, the way ownership and permissions are handled on your server, any 'wrapping' of scripts, deployment of mod_php or PHP as a CGI script.

Quote

Private Messages and Email

Please post your questions in forums instead of sending private messages to the administrators or moderators of the discussions. Doing so will enable the whole group to work on your problem. No matter how knowledgeable an individual is, inevitably people have different points of view and will offer different solutions. It only benefits you and the community when questions are answered in the public forums for all to read.

If any topic is found to be disregarding any of the Post Guidelines, you topic maybe locked, and repeat offenders maby banned without notice.

This Posting Guide created by Steve Knoblock (builder), administrator and forum moderator. Thanks to evilcoder and Miles Burton, Paul Gardner, Monk, Bane for starting and helping with this evolving text.

4
The Occasional Tutorial / Escaping The Labyrinth of PHP Includes
« on: May 04, 2003, 11:42:21 AM »
Escaping The Labyrinth of PHP Includes

In Brief: The include() feature of PHP bases paths on the location of the including script. This may leave you puzzling how to create a PHP page you can include anywhere on your website without modifying the include path for each folder. The solution is simple but may be somewhat confusing for those new to PHP. To include a file from any PHP page you must specify the actual location of the file relative to the file system instead of relative to the 'web root' or the root folder where web pages are served from. For example: include('/usr/www/users/youruserid/this.site/syndicate_the_news.php'); would include news in your site. If syndicate_the_news.php needs to include any text or php files, a database or XML parser module generating content, then you must ensure all includes in that file are 'absolute' or relative to the web root instead of to the folder of the executing script.

One of the great things about PHP pages is the ability to include content into a page from another source (included or generated from another PHP page, text file or HTML fragment). Placing included content anywhere on any page on your website is useful in reducing the amount of maintenance required to keep a website current. However, implementing this idea of universal includes can be difficult and frustrating to newcomers.

Why? Because of how PHP handles path names

You might think that it would be easy to include a piece of information on any page of your website. Just whip up a PHP page to generate some tasty HTML and include that page on whatever page you want the info to appear. You'd be wrong.

Let's look at why.

The first thing to study is the way PHP handles includes. (I know, study is boring, but often is revealing.)

The easiest way to include our information is to place the included page in same folder with the page doing the including.

baseball.php
Code: [Select]
<?php

// include from working folder
include('scores.php');

?>


To better organize our website we may prefer to gather all our include pages into a folder of their own. This is where the include business starts to get tricky.

baseball.php
Code: [Select]
<?php

// include from sub folder
include('includes/scores.php');

?>

The two kinds of includes we have looked at so far use what are called relative paths to the included files. The location of the include file is relative to the path of the location of the page doing the including. The path used to locate the include file is based on where the executing PHP page is located. In the first instance scores.php must always be in the same folder as baseball.php, which means we can place these pages anywhere on the site without changing the paths as long as we move both files together. This is a convenience because it does not tie the script to any one location.

Relative path. A relative path is one like this: folder/folder/php.php An absolute path is one like this: /root_web_folder/folder/folder/php.php The difference is subtle in syntax but important in meaning. The relative path is always relative to current folder the PHP page exists in. The absolute path is referenced from the web server root folder.

The second instance complicates our scenario a little. The path is still relative to the executing PHP page and we can also move the files about the site as long as they are kept in the same relation to one another (this means creating another 'includes' folder where they are moved to if one does not already exist). For many beginning PHP programmers it might seem possible that this piece of code could be included anywhere on the site. However, if you move this to a sub folder, the include will fail, unless there happens to be an include folder beneath that folder.

Suppose we have several sub folders each representing a different topic on our website. How do we include scores into the index page on all folders? If we try to use the previous include, it will fail when executed from any of the sub folders because the path is relative to where the PHP page is executing, therefore if 'includes/scores.php' is executed from the 'golf' folder the path will look like this: '/golf/includes/scores.php' It will fail because as you can see, no 'includes' folder exists within the golf folder. We want the includes folder to be centrally located off the main site folder. If we must create an includes folder off each topic folder that defeats the purpose of creating a centralized location for all included pages.


folders
Code: [Select]

/
/baseball
/football
/golf
/includes
/swimming


PHP allows us to use the Unix folder navigation symbols to locate a file relative to the current working folder. The two dots means move one folder level back toward the root folder. Now we can modify our index page in each folder to use the following code:

Code: [Select]
<?php

// include from sub folder
include('../includes/scores.php');

?>

This code looks one level back towards the root of the website folder tree (not the system root folder) and then back down into the 'includes' folder for the 'scores.php' file. Suppose we want to place the scores anywhere on our site? We have pages in several folders and we have an index page in our main folder. To place the scores on our index page we need:



Code: [Select]
<?php

// code for index.php

// include from sub folder
include('includes/scores.php');

?>

To place scores on pages in sub folders we need:


Code: [Select]
<?php

/****************************
 * code for
 * /baseball/index.php
 * /golf/index.php
 * etc.
 ***************************/

// include from sub folder
include('../includes/scores.php');

?>

Of course, the problem with this is we now must maintain different include paths for different pages. It would be nice to have just one piece of code we could use for any page on the site. Why not just include a header file on all pages? We would still have to use different relative paths on pages in different folders, but could we just include the scores something we include on every page? Suppose we also want to include a header on each page. We would have to include it the same way we included scores.php for pages on different folder levels. It might be possible then to keep scores.php in the includes folder along with the header.php and use a relative include, something like this:

We create a universal header called header.php (I'm not very inventive here am I?), placing it in the includes folder along with scores.php



Code: [Select]

/includes/header.php
/includes/scores.php




Code: [Select]
<?php

// universal header

// include folder
include('scores.php');

?>



We include it the same way we included scores.php on all our pages.


Code: [Select]
<?php

// code for index.php

// include from sub folder
include('includes/header.php');

?>


If you try this, which I encourage you to do, you will receive an error message. Why does this happen? We are making a relative include from header.php to another page in the same folder with it. What is wrong with including a page into an included page when they are in the same folder as one another?

Because the rule of paths being relative to the executing script applies to included pages also. Instead of the path to scores.php being relative to the location of header.php it is relative to the original including page, which may be in one level of the folder tree or another.



<b>The relative path to an include file in PHP is always based on the currently executing PHP page. This means if page a.php includes pages b.php and b.php includes c.php all relative include paths in b.php and c.php are relative to the location of a.php without exception.
</b>


As you can see, for a site of any magnitude this task is starting to be frustrating. What are the alternatives to using include files for placing scores on every page?

We can use an absolute path to the include file. This means giving up the easy ability to drag our PHP pages and drop them anywhere on the site without modification. To accomplish this we return to our original code used to include our scores from the 'includes' folder. By adding a single slash to the front of the include path we now reference our include from the main website folder. No matter what page we place this code on it will include scores.php from the same place.


Code: [Select]
&lt;?php

// include from sub folder
include('/includes/scores.php');

?&gt;


We can fetch our content from an external source, such as a database. Instead of a scores.php file we draw this information from a database. To make this easy to include on any page, we encapsulate this in a function. We can place this code anywhere on the website. By the way, the information does not have to come from a database, but can come from any external source not on the filesystem, such as fetching XML data from a website and translating it into formatted HTML, etc.


Code: [Select]
&lt;?php

// include scores here
display_scores();

?&gt;


We have to be careful that the function does not include anything from the file system, i.e. do any relative PHP includes. Otherwise, we are back to square one with the same problems we had before with relative includes and the same tradeoffs using absolute includes. This sometimes occurs when a database function depends on database abstraction layer or database configuration files in order to connect to the database.

Generating content from a function is also a good idea because the page or application does not have to know anything about the internals of the function generating the content. And it can be placed anywhere on any web page on our site. Except for the case in which the function itself resides in an file that must be included (as when functions are organized into one include file) or when database configuration and connection code must be included. Then we lose the modularity.

We can solve this problem by requiring any database configuration files to be absolute includes. (By the way this frustrates me because I have a philosophy born in my experience from making plain old static web pages that relative paths always best because it allows the document to be physically portable. But this probably does not matter as much for the include paths we specify in web applications. It's not like someone is going to save the application page itself on their hard drive and want to view it from there. I'm not talking about the paths used in links and image sources, but the includes. Paths for links and image sources created by your application may better serve users if they are relative (depending on your audience).

5
The Occasional Tutorial / Using Checkboxes for User Interaction
« on: May 04, 2003, 11:21:01 AM »
Using Checkboxes for User Interaction

Overview

The checkbox plays an important role in user interaction in many web applications (I apologize in advance for stupefying you with the term 'web application'; It's just that calling it a 'script' or 'PHP page' is too limiting and as a beginner it is helpful to start thinking of even the smallest scripts as applications. You'll thank me later.). A common use for checkbox inputs is to allow the user to select a number of items and carry out an operation on just those selected items. For example, deleting unwanted messages from a web based mailbox. They also can allow the user a way to configure application features or administrate content.

When used as part of a application interface, the user is typically presented with a list of items they can select by marking a checkbox beside each item. The list is contained within a HTML form so when user then submits the the form the items selected can be communicated to the application. Additional input may indicate what action the user wishes to take.

This approach is often better than a displaying links beside each item, one for each type of process. The checkbox approach is scalable in that any one of a number of actions can be applied to the selected items. It gives the user choice over what is done with the items. It also follows the familiar user interface process of selecting an 'object' before acting on it (the noun-verb metaphor).

Single Unrelated Checkbox Inputs

You are a probably familiar with seeing a checkbox input on a form. You should be familiar with web forms before attempting to use checkbox inputs in your applications.

Code: [Select]
<input type="checkbox" name="sideorder" value="Breadsticks" />Do you want breadsticks with your pizza?

The checkbox allows the user to select an item and communicate that selection to your application. When submitted as part of a form, if the checkbox input has been checked by the user the value will be available for use. If it has not been checked, the input name and value are not sent by the browser in the form submission. Neither will be available in your program. This means you can test for the existence of a checkbox name to see if it has been checked.


PHP Code: [Select]

print '<p>Side of</p>';
print 
'<ul class="sides">';
if(
$_POST['sideorder'])
{
	
print 
'<li>Breadsticks</li>';
}
print 
'</ul>';



Multiple Related Checkbox Inputs

A number of checkbox inputs may be grouped by name. These related checkbox inputs allows the user to select more than one item and communicate that selection of items to your application.

To return multiple values for a series of related checkbox inputs, PHP returns an array containing the values of any checked inputs. Checkbox inputs that are not checked do not appear in the array. The special status of related or multiple checkbox inputs is indicated by adding brackets to the input name (This may change from name to id attribute in the future).

Code for a series of checkboxes will appear very similar to this:

Code: [Select]
<input type="checkbox" name="topping[]" value="Extra Cheese" />
<input type="checkbox" name="topping[]" value="Green Pepper" />
<input type="checkbox" name="topping[]" value="Onion" />
<input type="checkbox" name="topping[]" value="Pepperoni" />
<input type="checkbox" name="topping[]" value="Italian Sausage" />
<input type="checkbox" name="topping[]" value="Anchovies" />


This property makes checkboxes useful for more than just selecting among items on a data entry form, but is an important tool in building administrative or user interfaces that control content or act on the user's wishes.  For example, it might allow the user to select multiple files for a web based file explorer or select a number of email items for deleting in a webmail application.

Using the Checkbox to Drive User Interaction

A checkbox interface is especially helpful for managing content that is displayed through tabular listings, which is the format most applications return query results in.


Let's review the process with a simple example that does not require any external input from a database. The checkbox items will be a static HTML form. The following code accepts the input from the Toppings form, printing those items that are checked.

Example 1

PHP Code: [Select]

<?php

if(isset($topping))
{
	
print 
'<p>Toppings:</p>';
	
// process items
	
$n count($topping);
	
for(
$i 0$i <= $n$i++)
	
{
	
	
print 
$topping[$i] . "<br />";
	
}
} else
{

?>

<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post" class="pizzaform" title="Pizza Toppings">
<input type="checkbox" name="topping[]" value="Extra Cheese" />Extra Cheese<br />
<input type="checkbox" name="topping[]" value="Green Pepper" />Green Pepper<br />
<input type="checkbox" name="topping[]" value="Onion" />Onion<br />
<input type="checkbox" name="topping[]" value="Pepperoni" />Pepperoni<br />
<input type="checkbox" name="topping[]" value="Italian Sausage" />Italian Sausage<br />
<input type="checkbox" name="topping[]" value="Anchovies" />Anchovies<br />
<input type="submit" value="Submit" />
</form>
<?php
}
?>



If the form has been submitted (this condition is detected by the checkbox having a value), the checked items are printed out.

This has been a very safe example. The only action was to print items. I wanted you to see this example before moving on to more serious applications the same principle. If we were deleting items in a database we could do some serious damage. Always backup any database you are working on, try to work on a development database before moving code to a production database and back that one up too before making any code changes.

Now, we will try the same thing in a database version. We will list items from a database and print those the use checks. We will also get a little fancy with our coding so that we do not have to write all those checkboxes out manually.

We will use the popular MySQL database in this example.


To help you understand the code, you need to know something about the database table we are listing items from. Imagine a database of films. Each film can have  annotations associated with it. We want a listing of the notes for a particular film. Each note has a unique identifier (also serving as primary key), the id of the film the notes are for and a shortened version of the item title. The first 32 characters of the note are used as a sort of title or abstract to identify the note as an aid to memory.

A function is used to generate each checkbox input. The make_item_control($title,$value) generates a table row with a checkbox input for inclusion in the form table. You could of course separate this out from the HTML table more, but for our example this is good enough.

Example 2

PHP Code: [Select]

<?php

// example code for checkbox.txt
// confirmed working: Friday, March 07, 2003

// Configuration information for connecting to database
// Contains $db_name, $db_user, $db_pass, $db_host
// for connection.

	
// Enter your database host name here.
	
$db_host "YourDatabaseHost";
	
// Enter your database password here.
	
$db_pass "YourDatabasePassword";
	
// Enter your database user name here.
	
$db_user "YourDatabaseUsername";
	
// Enter the name of your database here.
	
$db_name "YourDatabaseName";
	

	
// Connect to database
  
	
$db_conn = @mysql_pconnect($db_host$db_user$db_pass);
	

	
// Check for database unavailable 
	
if (!
$db_conn)
	
{
	
	
print 
"ERROR - failed to create connection: " mysql_error();
	
}

	

function 
make_item_control($value,$title) {
	

	
$content '<tr class="tabletext"><td><input type="checkbox" name="item[]" value="'.$value.'" />'.$title.'</td>';
	
return 
$content;
}

if(
$p_print_checked) {
	
// process items
	
$n count($item);
	
for(
$i 0$i <= $n$i++)
	
{
	
	
print 
urldecode($item[$i]) . "<br>";
	
}
} else {
	
// list items
	

	
// database query here
	

	
$sql "SELECT note_id,film_id,LEFT(text,32) AS item_name FROM note ORDER BY film_id ASC;";
	
$result mysql_db_query($db_name,$sql);
	
if (!
$result) {
	
	
	
	
print 
mysql_error() . ' ERROR - Select note query failed! ';
	
}
	
if (
mysql_num_rows($result) < 1) {
	
	
	
	
print 
'No notes in database.';
	
}
	
	
	

print 
'<form action='$_SERVER['PHP_SELF'] .'>';
print 
'<table>';
while(
$row mysql_fetch_array($result)) {
	
print 
make_item_control(urlencode($row[item_name]),$row[item_name]);
}
print 
'<tr class="tabletext">
	
<td>
	
<input type="Submit" name=p_print_checked value="Print Checked" />
	
</tr>'
;
print 
'</table>';
print 
'</form>';
}


?>



Suppose we want to delete comments that are obsolete. We can reuse the same code for printing checked items to delete selected items.

Example 3

PHP Code: [Select]

<?php

// example code for checkbox.txt
// confirmed working: Friday, March 07, 2003

// Configuration information for connecting to database
// Contains $db_name, $db_user, $db_pass, $db_host
// for connection.

	
// Enter your database host name here.
	
$db_host "YourDatabaseHost";
	
// Enter your database password here.
	
$db_pass "YourDatabasePassword";
	
// Enter your database user name here.
	
$db_user "YourDatabaseUsername";
	
// Enter the name of your database here.
	
$db_name "YourDatabaseName";
	

	
// Connect to database
  
	
$db_conn = @mysql_pconnect($db_host$db_user$db_pass);
	

	
// Check for database unavailable 
	
if (!
$db_conn)
	
{
	
	
print 
"ERROR - failed to create connection: " mysql_error();
	
}

	

function 
make_item_control($value,$title) {
	

	
$content '<tr class="tabletext"><td><input type="checkbox" name="item[]" value="'.$value.'" />'.$title.'</td>';
	
return 
$content;
}

if(
$p_delete_checked) {
	
// Process items
	
// We substract one from the count because a for loop executes once
	
// before incrementing.
	
$n count($item)-1;
	
for(
$i 0$i <= $n$i++)
	
{
	
	
$sql "DELETE FROM note WHERE note_id = $item[$i];";
	
	
$result mysql_db_query($db_name,$sql);
	
	
	

	
if (!
$result) {
	
	
	
	
print 
mysql_error() . ' ERROR - Delete note query failed! ';
	
	
	
}
	
	
	

	
}
} else {
	
// list items
	

	
// database query here
	

	
$sql "SELECT note_id,film_id,LEFT(text,32) AS item_name FROM note ORDER BY film_id ASC;";
	
$result mysql_db_query($db_name,$sql);
	
	
	

	
if (!
$result || mysql_num_rows($result) < 1) {
 print 
' ERROR - Select note query failed: ' .mysql_error();
	
	
	
}
	
	
	

print 
'<form action='$_SERVER['PHP_SELF'] .'>';
print 
'<table>';
while(
$row mysql_fetch_array($result)) {
	
print 
make_item_control($row[note_id],$row[item_name]);
}
print 
'<tr class="tabletext">
	
<td>
	
<input type="Submit" name=p_delete_checked value="Delete Checked" />
	
</tr>'
;
print 
'</table>';
print 
'</form>';
}


?>


Example Database Schema and Initial Values

The following is a database schema (a description of table structure) is provided so you can try the script for yourself. In addition there is SQL to populate the table with some initial values.


Code: [Select]
create table note (
note_id INT(11) NOT NULL AUTO_INCREMENT,
film_id INT(11) NOT NULL DEFAULT 0,
item_name varchar(255) NOT NULL DEFAULT '',
text TEXT  DEFAULT '',
cite_title varchar(255) NOT NULL DEFAULT '',
cite_link, varchar(255) NOT NULL DEFAULT '',

PRIMARY KEY note_id (note_id),
KEY item_id (film_id),
);

INSERT INTO note VALUES (100,16,'Lady Eastlake commented "It is now more than fifteen years ago that specimens of a new and mysterious art were first exhibited to our wondering gaze."','Eastlake, Photography','http://www.city-gallery.com/learning/');
INSERT INTO note VALUES (101,16,'"Not that
photographers flock especially to the metropolis; they are
wanted everywhere and found everywhere." provides ample evidence of the growth of photography in its earliest years.','Eastlake, Photography','http://www.city-gallery.com/learning/');
INSERT INTO note VALUES (102,16,'Lady Eastlake early on recognized the democratizing influence of photography, commenting that the pursuit "unites men of the most diverse lives, habits, and stations, so that whoever enters its ranks finds himself in a kind of republic..." a sentiment reminiscent of the early days of radio or the internet.','Eastlake, Photography','http://www.city-gallery.com/learning/');
INSERT INTO note VALUES (103,16,'Sir Charles Eastlake was first chairman of the Photographic Society, established in 1853, a newly instituted body for the support and recognition of the art of photography.','Eastlake, Photography','http://www.city-gallery.com/learning/');




Using While to Loop Through the Items

Although since its introduction in version 4 of PHP, foreach is the preferred way to iterate over an array, you may also use While to iterate over the checked items. For now, I leave that as an exercise for the reader.


All examples here are intended to generate output compatible with the XHTML 1.0 specification. See http://www.w3c.org for details.

6
General Database / Updated SQL Reference
« on: April 24, 2003, 12:59:15 PM »
I just wanted to mention the phphelp SQL reference pages have been cleaned up a bit and converted to PHP. If there's time (and if anyone wants to help) we may be able to expand them.

http://www.phphelp.com/ref/sql/

Steve

7
Suppose you would like your PHP pages to masquerade as .html files. How would you accomplish that?

If you are running PHP on the Apache web server platform, you can take advantage of issuing server directives from an .htaccess file in the root web folder or in any sub folder.

Include in you .htaccess file:

Code: [Select]
AddType application/x-httpd-php .html
If you are running PHP through a 'script wrapper' the code would look something like this:

Code: [Select]
Action application/x-myhost-sphp4 /cgi-bin/php-cgiwrap/myaccountname/php4.cgi
AddType application/x-myhost-sphp4 .php .html


You need to consult your individual hosting provider for details on how to invoke the wrapper, if any.

8
Solving Formatting Problems With Modulo (Or Fun With Modulo)

Making Tables More Readable With Alternating Row Colors

Typographers have known for a long time that tabular data is easier to read when presented with alternating colors for each row. Most people have at one time or another seen computer printer paper with the light green bars alternating with white. To give your web listings and tables greater readability add alternating row background colors.

The question is how to implement this. Some way of keeping track of which row we are on and assigning a color is needed. This tutorial is too short to go into all the various ways you might try to do this by brute force. Instead I will offer a technique whose origin is lost in the mists of programmer lore.

We will turn to modular arithmetic to do the trick. Most programming languages offer a modulo operator, which returns the remainder of a division. I will not go into modular arithmetic here, you can find detailed explanations by doing a web search on the topic. We are interested in a particular behavior of the modulo function. It has the curious property that if you take a number modulo a second number, the first number never exceeds the value of the second. In other words, it acts to limit the value of a variable and that value will "wrap around" back to zero no matter how large the first number becomes.

Suppose we want to limit a value to 256 (0-255) the amount a single byte can express.

Code: [Select]
0   modulo 256 = 0
100 modulo 256 = 100
255 modulo 256 = 255
256 modulo 256 = 0 (wraps around here)

The modulo is usually expressed in mathematical notation by mod as in 2 mod 7. In PHP, the modulo operator is the percent sign.

If we keep track of how many rows have been displayed we can use modulo to determine whether the row should use one color or another (given a total of two colors). We know that any number modulo will result in the following table:

Code: [Select]
(row, frequency, color)
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
4 % 2 = 0

Zero modulo two is zero, one modulo two is one, two modulo two is zero because we wrap around at the point the numbers are equal, any number greater than two continues this alternating pattern of one and zero.

This result is very useful. We now have a way of deciding for any given row which color should be displayed. If the result is 0, we display one color, if the result is 1, we display the alternate color for that row.

Here is a function I use frequently. Especially when displaying the output from relational database queries, which is naturally arranged into tables. This function returns either of two colors depending on a given row index. The colors are termed 'light' and 'dark' because typically alternating colors are designed to either alternate a light and dark color against which black type is readable. Typically white and light green or perhaps two light colors such as medium and light gray. The default parameters define white and gray when no colors are specified by the calling program.

Code: [Select]
function get_alt_row_color($i,$light_color="#ffffff",$dark_color="#e4e4e4") {
if ($i % 2 == 0) {
return $light_color;
} else {
return $dark_color;
}
}

You can call it directly in HTML code. When generating a HTML table, use something like this inside the loop:

Code: [Select]

/* ... looping through database records ... */

// code to generate a table row
$content .= '
<tr>
<td bgcolor="'. get_alt_row_color($i,$light_color="#ffffff",$dark_color="#eeeeee") .'">' $row[data]. '</td>
</tr>';

$i++; // increment row index

/* ... continue looping through database records ... */


Take note of how the function is used directly in string concatenation. This is a good technique: create a function that generates the text string you want, then drop it into the concatenation anywhere you want the output. Here the BGCOLOR attribute gets its value from the get_alt_row_color() function. This makes it portable, flexible and generic compared to a function that generates a predefined table row. A function is less error prone than repeating the same code everywhere.

There is another way to write code to alternate colors.

Code: [Select]
function get_alt_row_color($i) {

if ($i % 2 == 0) {
return '#FFFFFF';
} else {
return $GLOBALS['COLOR_ROW_ALT'];
}
}

This function takes its alternate color from a global variable, perhaps allowing the user to specify the alternate color in a configuration file. Calling the function is simplified by avoiding the color parameters and assuming the first color is white. Use your imagination to invent other more configurable functions.


Presenting Content in Two Columns

If you've read a newspaper then you are familiar with text arranged into columns. It is a very efficient way of displaying text and helps keep content at the top of the page reducing scrolling.

You might ask how do they do that when you see a dynamic website presenting varying content in two columns. How do they distribute content evenly between the two columns when they do not know the number of items until they are retrieved from a database or other source?

Modular arithmetic comes to the rescue again. First we find the number of items in the content. Then we calculate a division point where items will go into one column or the other. For two columns this division point is about half the number of items. We will use half the number of items as our division point.

Once we have these values, we can begin looping through the query results, array or list of items. In this example the array is from a database query result. However, it could be any array, we could just pass the function an array along with the division point.

Code: [Select]
function make_columns_from_array($result,$division_point) {
$division_point = mysql_num_rows($result) / 2;

$i=0;
while ( $row = mysql_fetch_array($result) )
{
$item = sprintf("<p class=item><b><a href="$PHP_SELF?category=%s">%s</a></b> (%s)<br><span class=description>%s</span></p>",$row[category_id],decat($row[category_title]),$row[items],$row[category_description]);

if($i % $division_point) {
$a .= "$item";
}
else {
$b .= "$item";
}
$i++; // increment index
}
$content = '
<table>
<tr valign="top">
<td>'. $a; .'</td>
<td>'. $b; .'</td>
</tr>
</table>';
return $content;
}


Using modulo we place an item in one of two strings, $a or $b distributing them between the columns. After that we put the $a items in the left table column and the $b items in the right column. There are probably more elegant and efficient ways to do this. I leave that to others.

Modular Arithmetic

The code in this tutorial is based on modular arithmetic. It is so useful in programming that the  modulo operator appears in nearly all computer languages and has been used since the dawn of programming for all kinds of tricks. It is well worth your time learning about it.



    Clock (Modular) Arithmetic - Easy to understand explanation.
    Modular Arithmetic - Mathematical and algebraic explanation.
    Google Search for Modular Arithmetic

Pages: [1]