Dynamic Web Content with PHP

The material from September 29th's lecture continues last week's with another tutorials on-line: http://www.phpcatalyst.com/PHP_String_Manipulation.

Looping Statements

Mary's bundled images are available via this link here.

Tonight we demonstrate the two most basic loops using a digitized gallery of paintings from Mary Ellis.
The full code is presented at the bottom of this document. You will diagram the code to the best of your ability using your tool of choice (Word processor, Dreamweaver, HTML editor, etc.)..

The While Loop

We can show all her paintings as thumbnails using a while loop:


	<table border=0 cellpadding=5 cellspacing=0 width=100%>
            <tr>
            <?
				$i=1;
				$base_url = "http://artstar.org/community/virtual_artists/mellis/";
				while ($i<=21) {
					echo '		<td width=100% valign=top><a href="'.$base_url.$i.'.jpg"><img src="../../../risd/artstar/mellis/Picture '.$i++.'.png" width=64></a></td>';
					echo "\n";
				}
			?>
            </tr>
	</table>
Remember that the while statement executes a block of code if and as long as a specified condition evaluates to true. If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop.

The For Loop

Let's look at another presentation of the gallery thumbnails using a for Loop:


	<table border=0 cellpadding=5 cellspacing=0 width=100%>
            <?
				$i=1;
				$base_url = "http://artstar.org/community/virtual_artists/mellis/";
            	echo '<font COLOR="red" face=Verdana>Mary Ellis</font>';
				for ($j=0; $j<6; $j++) {
					echo '	<tr>';
					echo "\n";
					echo '		<td width=100% valign=top><a href="'.$base_url.$i.'.jpg"><img src="../../../risd/artstar/mellis/Picture '.$i++.'.png"></a></td>';
					echo "\n";
					echo '		<td width=100% valign=top><a href="'.$base_url.$i.'.jpg"><img src="../../../risd/artstar/mellis/Picture '.$i++.'.png"></a></td>';
					echo "\n";
					echo '		<td width=100% valign=top><a href="'.$base_url.$i.'.jpg"><img src="../../../risd/artstar/mellis/Picture '.$i++.'.png"></a></td>';
					echo "\n";
					echo '	</tr>';					
					echo "\n";
				}
			?>
	</table>

The For statement loop is used when you know how many times you want to execute a statement or a list of statements. For this reason, the For loop is known as a definite loop. The syntax of For loops is a bit more complex, though for loops are often more convenient than While loops. The For loop syntax is as follows: 

for (initialization; condition; increment)
{
   code to be executed;
}

The For statement takes three expressions inside its parentheses, separated by semi-colons. When the For loop executes, the following occurs:

  • The initializing expression is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.
  • The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the For loop terminates.
  • The update expression increment executes.
  • The statements execute, and control returns to step 2.

Review the very simple example that prints out numbers from 0 to 10:

Break and Continue Statements

Sometimes you may want to let the loops start without any condition, and allow the statements inside the brackets to decide when to exit the loop. There are two special statements that can be used inside loops: Break and Continue.

The Break statement terminates the current While or For loop and continues executing the code that follows after the loop (if any). Optionally, you can put a number after the Break keyword indicating how many levels of loop structures to break out of. In this way, a statement buried deep in nested loops can break out of the outermost loop.

Examples below show how to use the break statement:

<?php
echo "<p><b>Example of using the Break statement:</b></p>";

for ($i=0; $i<=10; $i++) {
   if ($i==3){break;} 
   echo "The number is ".$i;
   echo "<br />";
}

echo "<p><b>One more example of using the Break statement:</b><p>";

$i = 0;
$j = 0;

while ($i < 10) {
  while ($j < 10) {
    if ($j == 5) {break 2;} // breaks out of two while loops
    $j++;
  }
  $i++;
}

echo "The first number is ".$i."<br />";
echo "The second number is ".$j."<br />";
?>

The Continue statement terminates execution of the block of statements in a While or For loop and continues execution of the loop with the next iteration:

<?php
echo "<p><b>Example of using the Continue statement:</b><p>";

for ($i=0; $i<=10; $i++) {
   if (i==3){continue;} 
   echo "The number is ".$i; 
   echo "<br />";
}
?>

Back to top

String Manipulations

In this section, we will learn different ways of manipulating string through PHP coding. Some of these are basic coding techniques while some will require using built-in functions of PHP for advance string manipulation.

String Concatenation

One of the most simplest string manipulation activity that can be done is concatenating two or more strings to form a single string. For example: $a might hold a string called "First" and $b might hold a string called "Second". To concatenate these two strings into one, we use a '.' (dot). See this example:

<?php
$a 
"First";
$b "Second";
$c "Third";

echo 
$a $b//using a . (dot) in between $a and $b

echo $a $b $c//three strings together

$d $a $b//concatenating $a, $b and storing in $d

echo $d//printing $d

echo "\$a is holding a string called"." ".$a;  
?>

Change the case of a string to lowercase and UPPERCASE

That's quite easy! All we need to do is use the built-in function called strtolower() to convert a string to lowercase and strtoupper() for uppercase conversions. See the example to convert a string to lowercase and uppercase.

<?php
$string 
"PHP is a GREAT Programming Language!";
$new_string strtolower($string);

echo 
$new_string;
//Output: php is a great programming language!

$new_string strtoupper($string);

echo 
$new_string;
//Output: PHP IS A GREAT PROGRAMMING LANGUAGE!
?>

Now, use the above example but replace the used functions with ucwords() (Uppercase the first character of each word in the string) and also ucfirst().

Determining position of first occurrence of a string

This is easy one! We will use yet another handy built-in function called strpos(). The syntax of strpos() is:

strpos ( string, keyword [, int offset] )

This will return 'FALSE' if the keyword is not found in the string and you will have to use '===' (strict comparison) to check the returned value. See the below example for usage of strpos().

<?php
$string 
"PHP is a GREAT Programming Language!";
$keyword "GREAT";

#Searching for keyword in the string
$position strpos($string$keyword);

echo 
$position//Output: 9 (9th position of Keyword)
?>

<?php
#conditional usage of strpos()
$string "This is a simple string";
$keyword "simple";
$keyword_1 "MySQL";

if (
strpos($string$keyword) > ) {
    echo 
"String found";
    } else {
    echo 
"String not found";
    }
?>

<?php
#conditional usage of strpos()
$string "This is a simple string";
$keyword "MySQL";

if (
strpos($string$keyword) > ) {
    echo 
"String found";
    } else {
    echo 
"String not found";
    }
?>

Return portion of a string from a given string

To get portion of a string from a given string we will make use of substr() function of PHP. The syntax is:

substr ( string , int start [, int length] )

Remember, the position of the first character of the string is always '0'. The function will take the start position and return a portion of the string from the start position as specified. You may optionally also mention the end position till which you want to get the portion of any given string. For example, in the string "Hello", the letter 'H' is at position '0' and the letter 'o' is at position '4'. See this example:

<?php
$string 
"PHP is GREAT Programming Language!";

#Returning portion of the above string from 0 to 12
$str substr($string,0,12);

echo 
$str//Output: PHP is GREAT (includes two spaces as well)

#Let's also concatenate something to $str

echo $str." Programming Language!";
?>

Adding slashes to string

Under various circumstances, you will need to automatically add slashes to escape special characters in a string. Be it storing in database table, or for anything else. Here's how we can do it with built-in addslashes() function. The syntax is:

addslashes ( string )

Below is an example to add slashes to any given string.

<?php
$string 
"Let's learn PHP. It's fun!";
$new_string addslashes($string);
echo 
$new_string//output: Let\'s learn PHP. It\'s fun!

#You can also do this directly without storing it in $new_string
echo addslashes($string); //works too! 
?>

Artist Gallery Code

see: http://artstar.org/community/virtual_artists/mellis/

<?php include("header.php") ?>
<script type="text/javascript">
<!--
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) { d=document; } if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p); }
if(!(x=d[n])&&d.all) { x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; }
for(i=0;!x&&d.layers&&i<d.layers.length;i++) { x=MM_findObj(n,d.layers[i].document); }
if(!x && d.getElementById) { x=d.getElementById(n); } return x;
}

function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) {
if ((x=MM_findObj(a[i]))!=null) { document.MM_sr[j++]=x; if(!x.oSrc) { x.oSrc=x.src; } x.src=a[i+2]; }
} }
//-->
</script>
</head>

<body onLoad="MM_preloadImages('full/full2.png','full/full3.png','full/full6.png',
'full/full7.png','full/full8.png','full/full9.png','full/full10.png','full/full12.png',
'full/full13.png','full/full14.png','full/full5.png')">
<table border=0 cellpadding=0 cellspacing=0 width=1002>
<tr> <td> <form action="index.php"method="post" style="font-family: Arial, Helvetica, sans-serif">
<table width=1256 height="658" border=0 align="center" cellpadding=0 cellspacing=0><tr><td valign="bottom"><table width=1141 height="656" border=0 align="center" cellpadding=0 cellspacing=0>
<tr>
<td width="200" rowspan="3" align="left" valign="top"><p><img src="star.png" width="200" height="192">

<?php

//check for form submission:
if (isset($_POST['submitted'])) {
// minimal form validation
if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['comments']) ) {

//create the body:
$body="email: {$_POST['email']}\n\nComments: {$_POST['comments']}";

//70 char max
$body=wordwrap($body, 70);

//send the email.
mail('mary.ellis@gmail.com', 'Contact Form Submission', $body, "From: {$_POST['email']}");

//print a message:
echo '<p><em>Thank you for contacting me at '. date('g:i a (T)').' on '. date('l F j, Y') .'.</em></p>';

//time it took to submit form
echo '<p><strong> It took ' . (time() - $_POST['start']) . ' seconds for you to complete and submit the form. </strong></p>';

$_POST=array();
} else {
echo 'Please fill out the form completely.</p>';
}
} //end of main isset() IF.
else { //create the HTML form:
?>
</p>
<p>&nbsp; </p>
<h1 style="font-family: Arial, Helvetica, sans-serif; font-size: large">Contact the Artist</h1>
<p style="font-family: Arial, Helvetica, sans-serif; font-size: 12px">Please fill out this form to contact the artist.</p>
<p style="font-size: 12px">Name:<br />
<input type ="text" name="name" size="30" maxlength="60" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>" />
</p>
<p style="font-size: 12px">Email Address:
<br />
<input type ="text" name="email" size="30" maxlength="80" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" />
</p>
<p style="font-size: 12px">Comments:
<br />
<textarea name="comments" rows="5" cols="30"><?php if (isset($_POST['comments'])) echo $_POST['comments']; ?>
</textarea>
</p>
<p>
<input type="submit" name="submit" value="send!" />
</p>
<input type="hidden" name="start" value="<?php echo time(); ?>" />
<input type="hidden" name="submitted" value="TRUE" /> &nbsp;
<?php
} //end of create HTML form.
?>
</td>
</tr>
<tr>
<td valign="top">
<table border =0 cellpadding=5 cellspacing=0 align=center width=200>
<?
$i=1;
$base_url = "http://artstar.org/community/virtual_artists/mellis/";
for ($j=0; $j<3; $j++) {
echo '<tr>';
echo '<td width=100% valign=top align=center><a href="'.$base_url.$i.'.jpg" target="_blank"><img src="full/full'.$i.'.png" border=0 width=70 height=70 id="t'.$i.'" onMouseOver="MM_swapImage(\'full1\',\'\',\'full/full'.$i++.'.png\',1)" onMouseOut="MM_swapImgRestore()" /></a></td>';
echo "\n";
echo '<td width=100% valign=top align=center><a href="'.$base_url.$i.'.jpg" target="_blank"><img src="full/full'.$i.'.png" border=0 width=70 height=70 id="t'.$i.'" onMouseOver="MM_swapImage(\'full1\',\'\',\'full/full'.$i++.'.png\',1)" onMouseOut="MM_swapImgRestore()" /></a></td>';
echo "\n";
echo '<td width=100% valign=top align=center><a href="'.$base_url.$i.'.jpg" target="_blank"><img src="full/full'.$i.'.png" border=0 width=70 height=70 id="t'.$i.'" onMouseOver="MM_swapImage(\'full1\',\'\',\'full/full'.$i++.'.png\',1)" onMouseOut="MM_swapImgRestore()" /></a></td>';
echo "\n";
echo '<td width=100% valign=top align=center><a href="'.$base_url.$i.'.jpg" target="_blank"><img src="full/full'.$i.'.png" border=0 width=70 height=70 id="t'.$i.'" onMouseOver="MM_swapImage(\'full1\',\'\',\'full/full'.$i++.'.png\',1)" onMouseOut="MM_swapImgRestore()" /></a></td>';
echo "\n";
echo '<td width=100% valign=top align=center><a href="'.$base_url.$i.'.jpg" target="_blank"><img src="full/full'.$i.'.png" border=0 width=70 height=70 id="t'.$i.'" onMouseOver="MM_swapImage(\'full1\',\'\',\'full/full'.$i++.'.png\',1)" onMouseOut="MM_swapImgRestore()" /></a></td>';
echo "\n";
echo '<td width=100% valign=top align=center><a href="'.$base_url.$i.'.jpg" target="_blank"><img src="full/full'.$i.'.png" border=0 width=70 height=70 id="t'.$i.'" onMouseOver="MM_swapImage(\'full1\',\'\',\'full/full'.$i++.'.png\',1)" onMouseOut="MM_swapImgRestore()" /></a></td>';
echo "\n";
echo '<td width=100% valign=top align=center><a href="'.$base_url.$i.'.jpg" target="_blank"><img src="full/full'.$i.'.png" border=0 width=70 height=70 id="t'.$i.'" onMouseOver="MM_swapImage(\'full1\',\'\',\'full/full'.$i++.'.png\',1)" onMouseOut="MM_swapImgRestore()" /></a></td>';
echo "\n";
echo '</tr>';
}

//echo iterations= # of columns and $j<# = # of rows
?>
</table>
</td>
</tr>
<tr>
<td align="center" valign="top"><p align="center"><img src="full/full1.png" name="full1" width="450" height="450" align="middle" id="full1" /></p></td>
<td valign="bottom">&nbsp;</td>
</tr>
</table>
</td>
</tr>
</table>
</form></td>
</tr>
</table>
<p>&nbsp;</p>
<?php include("footer.php") ?>