0% found this document useful (0 votes)
10 views

PHP Lab Manual

Uploaded by

ephitsegaye7878
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

PHP Lab Manual

Uploaded by

ephitsegaye7878
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Wollo University

Kombolcha institute of Technology


Department of Information System

1. <html>
<head>
<title>Hello World!</title>
</head>
<body>
<?php
// single-line comments can be like this
# or even like this
/* multi-line comments can
be like this */ ?>
<h1>Examples</h1>
<?php echo "Hello World!"; ?><br />
<?php
// The semicolon at the end of the statement is important!
?>
<?php
// print works like echo
print "Hello World!";
?><br />

<?php
// concatenation
echo "Hello" . " World!<br />";

// simple math
echo 2 + 3;

?><br />
</body>
</html>
1. <?php
/* WARNING: NEVER include this file on your production machine
It's very useful for development but it also gives away WAY too much
information about your system if anyone got access to it.
*/
phpinfo();
?>
2. <html>
<head>
<title>Variables</title>
</head>

PHP Lab Manual Prepared By Seid H. Page 1


<body>
<?php /*
start with a $, followed by letter or underscore
can contain letters, numbers, underscores, or dashes, but no spaces
case-sensitive
*/ ?>

<?php
$var1 = 10;
echo $var1;

// $myVariable and $myvariable are different


$my_variable = "Hello World";
$my_Variable = "Hello World Again";
echo $my_Variable;
echo "<br />";
?>

<?php
// variables values are variable; $var1 can be assigned a new value
$var1 = 100;
echo $var1;
?>
</body>
</html>
3. <html>
<head>
<title>Strings</title>
</head>
<body>
<?php
// Simple string, surrounded by single quotes.
// (included HTML still works just like HTML when output)
echo 'Hello World<br />';

// Simple string, surrounded by double quotes. (best practice)


echo "Hello World<br />";

// Strings can be assigned to variables


$my_variable = "Hello World";
echo $my_variable;
echo "<br />";

// and concatenated with other strings or variables containing strings


echo $my_variable . " Again";
?>

PHP Lab Manual Prepared By Seid H. Page 2


<br />
<?php
// PHP will substitute the value of a string for a variable inside double-
quotes
echo "$my_variable Again.<br />";

// curly brackets can help make this substitution clearer


// sometimes required to help PHP know that it is a variable
// e.g. "{$hour}am" is clear while $houram is not
// (best practice)
echo "{$my_variable} Again.<br />";

// Variable substitution does not take place inside single quotes


echo '$my_variable Again.<br />';
?>
</body>
</html>
4. <html>
<head>
<title>String Functions</title>
</head>
<body>

<?php
$firstString = "The quick brown fox";
$secondString = " jumped over the lazy dog.";
?>
<?php
// Concatentation
$thirdString = $firstString;
$thirdString .= $secondString;
echo $thirdString;
?>
<br />
Lowercase: <?php echo strtolower($thirdString); ?><br />
Uppercase: <?php echo strtoupper($thirdString); ?><br />
Uppercase first-letter: <?php echo ucfirst($thirdString); ?><br />
Uppercase words: <?php echo ucwords($thirdString); ?><br />
<br />
Length: <?php echo strlen($thirdString); ?><br />
Trim: <?php echo $fourthString = $firstString . trim($secondString);
?><br />
Find: <?php echo strstr($thirdString, "brown"); ?><br />
Replace by string: <?php echo str_replace("quick", "super-fast",
$thirdString); ?><br />

PHP Lab Manual Prepared By Seid H. Page 3


</body>
</html>
5. <html>
<head>
<title>Numbers</title>
</head>
<body>
<?php
$var1 = 3;
$var2 = 4;
?>

Basic Math: <?php echo ((1 + 2 + $var1) * $var2) / 2 - 5; ?><br />


<br />

<?php // You can perform math operations directly on values ?>


+=: <?php $var2 += 4; echo $var2; ?><br />
-=: <?php $var2 -= 4; echo $var2; ?><br />
*=: <?php $var2 *= 3; echo $var2; ?><br />
/=: <?php $var2 /= 4; echo $var2; ?><br />
<br />

Increment: <?php $var2++; echo $var2; ?><br />


Decrement: <?php $var2--; echo $var2; ?><br />

</body>
</html>
6. <html>
<head>
<title>Numbers: Floating Point Numbers</title>
</head>
<body>
<?php
// Floating Point Numbers (floats) are "numbers with a decimal"
$var1 = 3.14
?>
<?php
// Floats can occur when two numbers don't divide evenly
echo 4/3;
?>

Floating point: <?php echo $myFloat = 3.14; ?><br />


Round: <?php echo round($myFloat, 1); ?><br />
Ceiling: <?php echo ceil($myFloat); ?><br />
Floor: <?php echo floor($myFloat); ?><br />

PHP Lab Manual Prepared By Seid H. Page 4


</body>
</html>
7. <html>
<head>
<title>Arrays</title>
</head>
<body>
<? /*
Think of an array like an expandable file folder where you can put
items in each of the pockets
There are no limits to how many pockets it can have (not that
you'll need to worry about at least)
Then you can reference those items by the pocket number (or
"index")
(This is the "value" of that "position" in the array)
Be careful! Pockets are numbered starting at 0 (0,1,2,3...) so the
index of the 2nd pocket is 1
*/?>

<?php
// defining a simple array
$array1 = array(4,8,15,16,23,42);

// referencing an array value by its index


echo $array1[0];

// arrays can contain a mix of strings, numbers, even other arrays


$array2 = array(6,"fox", "dog", array("x", "y", "z"));

// referencing an array value that is inside another array


echo $array2[3][1];
?>
<br />
<?php
// Changing values in an array that has already been defined
// It's just like variables but you use the index to reference the array
position
$array2[3] = "cat";
echo $array2[3];
?>
<br />
<?php
// You can also assign labels to each pocket (called "keys"),
$array3 = array("first_name" => "Kevin", "last_name" =>
"Skoglund");

PHP Lab Manual Prepared By Seid H. Page 5


// which will allow you to use the key to reference the value in that
array position.
echo $array3["first_name"] . " " . $array3["last_name"] . "<br />";
$array3["first_name"] = "Larry";
echo $array3["first_name"] . " " . $array3["last_name"] . "<br />";
?>

<br />
A good way to see the values inside an array during development:<br />
<pre><?php print_r($array2); ?></pre>
</body>
</html>
8. <html>
<head>
<title>Array Functions</title>
</head>
<body>
<?php $array1 = array(4,8,15,16,23,42); ?>

Count: <?php echo count($array1); ?><br />


Max value: <?php echo max($array1); ?><br />
Min value: <?php echo min($array1); ?><br />
<br />
Sort: <?php sort($array1); print_r($array1); ?><br />
Reverse Sort: <?php rsort($array1); print_r($array1); ?><br />
<br />
<?php
// Implode converts an array into a string using a "join string"
// Explode converts a string into an array using a "divide string"
?>
Implode: <?php echo $string1 = implode(" * ", $array1); ?><br />
Explode: <?php print_r(explode(" * ", $string1)); ?><br />
<br />
In array: <?php echo in_array(15, $array1); // returns T/F ?><br />

</body>
</html>
9. <html>
<head>
<title>Loops: foreach</title>
</head>
<body>
<?php /* foreach loops

foreach (array_expression as $value)


statement;

PHP Lab Manual Prepared By Seid H. Page 6


foreach (array_expression as $key => $value)
statement;

Works only on arrays!


*/ ?>

<?php
$ages = array(4, 8, 15, 16, 23, 42);
?>

<?php
// using each value
foreach($ages as $age) {
echo $age . ", ";
}
?>
<br />
<?php
// using each key => value pair
foreach($ages as $position => $age) {
echo $position . ": " . $age . "<br />";
}
?>
<br />
<?php
// Just for fun...
$prices = array("Brand New Computer"=>2000,
"1 month in Lynda.com Training Library"=>25,
"Learning PHP" => "priceless");
foreach($prices as $key => $value) {
if (is_int($value)) {
echo $key . ": $" . $value . "<br />";
} else {
echo $key . ": " . $value . "<br />";
}
}
?>

</body>
</html>

10. <html>
<head>
<title>Booleans and NULL</title>

PHP Lab Manual Prepared By Seid H. Page 7


</head>
<body>
<?php
/* Booleans are used to represent the concepts of true and
false.
They are most often used for testing if a statement is true or
false and
they'll play a bigger role when we discuss logical
expressions.
Note that there is a difference between
boolean true/false and the strings "true"/"false".
*/
$bool1 = true;
$bool2 = false;

// When booleans are displayed, PHP will attempt to convert them


into a string
// You'll get either "1"/"0" or "1"/"" instead of true/false
?>
$bool1: <?php echo $bool1; ?><br />
$bool2: <?php echo $bool2; ?><br />
<br />
<?php
/* NULL is used to represent the concept of nothing or the
state of being empty
In the below example three variable have been set,
then boolean tests are performed and the results are
output as a string
*/
$var1 = 3;
$var2 = "cat";
$var4 = NULL;

// isset tests whether a variable has been set


// It returns true or false as a result of the test.
?>
$var1 is set: <?php echo isset($var1); // result: true ?><br />
$var2 is set: <?php echo isset($var2); // result: true ?><br />
$var3 is set: <?php echo isset($var3); // result: false ?><br />
<?php unset($var1); ?>
$var1 is set: <?php echo isset($var1); // result: false ?><br />
$var2 is set: <?php echo isset($var2); // result: true ?><br />
$var3 is set: <?php echo isset($var3); // result: false ?><br />
<br />
<?php // empty test whether a variable is empty ?>
$var1 empty: <?php echo empty($var1); // result: true ?><br />

PHP Lab Manual Prepared By Seid H. Page 8


$var4 empty: <?php echo empty($var4); // result: true ?><br />
</body>
</html>
11. <html>
<head>
<title>Type Casting</title>
</head>
<body>
<?php
// PHP will try to convert between types (strings, number, arrays,
etc.) as best it can

// Sometimes it will make educated guesses as to what you mean


// For example, if you add a string and a number like this:
$var1 = "2 brown foxes";
$var2 = $var1 + 3;
echo $var2;
?>
<br />
<?php
// gettype will retrieve an item's type
echo gettype($var1); echo "<br />";
echo gettype($var2); echo "<br />";

// settype will convert an item to a specific type


settype($var2, "string");
echo gettype($var2); echo "<br />";

// Or you can specify the new type in parentheses in front of the


item
$var3 = (int) $var1;
echo gettype($var3); echo "<br />";
?>
<?php // You can also perform tests on the type (which return booleans)
?>
is_array: <?php echo is_array($var1); // result: false ?><br/>
is_bool: <?php echo is_bool($var1); // result: false ?><br/>
is_float: <?php echo is_float($var1); // result: false ?><br />
is_int: <?php echo is_int($var1); // result: false ?><br/>
is_null: <?php echo is_null($var1); // result: false ?><br/>
is_numeric: <?php echo is_numeric($var1); // result: false ?><br />
is_string: <?php echo is_string($var1); // result: true ?><br />

</body>
</html>

PHP Lab Manual Prepared By Seid H. Page 9


12. <html>
<head>
<title>Constants</title>
</head>
<body>
<?php
/* Constants can't change their values after being defined
Constant names use all capital letters and no dollar sign
*/

// Assignment to a variable
$max_width = 980;
// Assignment to a constant
define("MAX_WIDTH", 980);

// Referencing the value of a constant


echo MAX_WIDTH; echo "<br />";

// Trying to change a constant will give an error:


// MAX_WIDTH += 1;

// But changing a variable will not.


$max_width += 1;
echo $max_width;

/*
Note that once a page is returned, a constant CAN be redefined by another PHP page.
For example:
Browser Request 1 -> page1.php -> SIZE defined as 10 -> PHP page finishes -> Page 1
Returned
Browser Request 2 -> page2.php -> SIZE defined as 20 -> PHP page finishes -> Page 2
Returned

SIZE must remain 10 throughout page1.php,


but when the 2nd request comes in SIZE is not defined
*/
?>
</body>
</html>
13. <html>
<head>
<title>Logical Expressions</title>
</head>
<body>
<?php /* if-statements

PHP Lab Manual Prepared By Seid H. Page 10


if (expression)
statement;

does NOT require semicolons except after statements


{} go around multi-line if-statements
{} are optional for single-line if-statments but I strongly suggest
them
expressions always evaluate to a boolean value (true/false)
expressions can use comparison operators (==, !=, >, <, >=, <=)
*/ ?>

<?php
$a = 4;
$b = 4;
if ($a > $b) {
echo "a is larger than b";
}
?>

</body>
</html>
14. <html>
<head>
<title>Logical Expressions: Switch</title>
</head>
<body>
<?php
/* switch
Useful when there are many possible actions based on the value of
single variable
*/

$a = 2;

switch ($a) {
case 0:
echo "a equals 0";
break;
case 1:
echo "a equals 1";
break;
case 2:
echo "a equals 2";
break;
default:
echo "a is not 0, 1, or 2";

PHP Lab Manual Prepared By Seid H. Page 11


break;
}
?>
</body>
</html>
15. <html>
<head>
<title>Loops: while</title>
</head>
<body>
<?php /* while loops

while(expression)
statement;

{} around multi-line statements (like if-statements)


watch out for infinite loops
*/

// This loop outputs 0-10


$count = 0;
while ($count <= 10) {
echo $count . ", ";
$count++;
}
echo "<br />Count: {$count}";
?>
<br />
<?php
// Loops can be combined with if-statements
$count = 0;
while ($count <= 10) {
if ($count == 5) {
echo "FIVE, ";
} else {
echo $count . ", ";
}
$count++;
}
echo "<br />Count: {$count}";
?>

</body>
</html>
16. <html>
<head>

PHP Lab Manual Prepared By Seid H. Page 12


<title>Loops: for</title>
</head>
<body>
<?php /* for loops

for (expr1; expr2; expr3)


statement;

semicolons separate three expressions:


expr1 executed at start (initialize)
expr2 evaluated at the start of each loop, continues as long as it is
TRUE
expr3 executed at the end of each loop

{} around multi-line statements (like if-else)


watch out for infinite loops
*/ ?>

<?php
// Outputs 1-10
for ($count=0; $count <= 10; $count++) {
echo $count . ", ";
}
?>
</body>
</html>
17. <html>
<head>
<title>Loops: break</title>
</head>
<body>
<?php /* break

Breaks out of a loop immediately without performing remaining


statements or further loop cycles

*/

// Notice that the for loops had a comma after 10


// We could fix that this way:
for ($count=0; $count <= 10; $count++) {
echo $count;
if ($count == 10) { break; }
echo ", ";
}
?>

PHP Lab Manual Prepared By Seid H. Page 13


</body>
</html>
18. <html>
<head>
<title>Loops: continue</title>
</head>
<body>
<?php /* continue
Imagine that every loop has an implicit "continue" at the end

You can also have an explicit "continue" which will loop back to the top
immediately
i.e. skip the remaining statements and start the next cycle of the
loop
Useful if you can quickly determine that the rest of the loop contents won't
apply
If you can, it could speed up your loop!
*/ ?>

<?php
// skips the number 5
for ($count=0; $count <= 10; $count++) {
if ($count == 5) {
continue;
}
echo $count . ", ";
}
?>
</body>
</html>
19. <html>
<head>
<title>Loops: pointers</title>
</head>
<body>
<?php // Pointers and while loops revisited

$ages = array(4, 8, 15, 16, 23, 42);


?>
<?php
// Arrays have pointers that point to a position in the array
// We can use current, next and reset to manipulate the pointer
echo "1: " . current($ages) . "<br />";
next($ages);
echo "2: " . current($ages) . "<br />";

PHP Lab Manual Prepared By Seid H. Page 14


reset($ages);
echo "3: " . current($ages) . "<br />";
?>
<br />
<?php
// while loop that moves the array pointer
// It is important to understand this type of loop before working with
databases
while ($age = current($ages)) {
echo $age . ", ";
next($ages);
}
?>
</body>
</html>
20. <html>
<head>
<title>Functions</title>
</head>
<body>
<?php /* User-defined functions

function name($argument1, $argument2 ...) {


statement
}

does NOT require semicolons except after statements


{} go around function statements

Functions can call any PHP code, even other functions

Function name can contain letters, numbers, underscores, dashes (no


spaces)
but name must start with a letter or underscore
Names are case-insenstive but it is better to call them exactly as they were
defined

In PHP3, functions must be defined prior to calling them


In PHP4/5, can appear anywhere (base-level functions are pre-processed)

Once defined, functions can be called from anywhere


Once defined, functions can't be redefined

Avoid declaring functions inside functions or conditionals while you are


beginner.
(It's no problem for you to CALL functions from inside funtions though!)

PHP Lab Manual Prepared By Seid H. Page 15


*/ ?>

<?php
// a simple function
function say_hello() {
echo "Hello World!<br />";
}
say_hello();

// a function with 1 argument


function say_hello2($word) {
echo "Hello {$word}!<br />";
}
say_hello2("World");
// functions must be called with the same number of arguments as were
defined

// Functions can be called more than once (that's the point!) with different
arguments
say_hello2("Everyone");

?>
</body>
</html>
21. <html>
<head>
<title>Functions: globals</title>
</head>
<body>
<?php /* global variables in functions

Variables inside a function aren't the same as the variable outside it

Declaring a variable as global "pulls in" the variable


as it exists outside the function so that the function can use it.
*/

// Example using a global variable


$bar = "outside";
function foo() {
global $bar;
$bar = "inside";
}
foo();
// guess which this will return before you try it

PHP Lab Manual Prepared By Seid H. Page 16


echo $bar . "<br />";

?>
<br />
<?php
// Example using a local variable, arguments and return values
$bar = "outside";
function foo2($var) {
$var = "inside";
return $var;
}
$bar = foo2($bar);
echo $bar . "<br />";

// use sparingly for variables which truly are global & need to be accessed many
times from many places
// don't declare globals out of laziness--pass in arguments and return values
instead
?>
</body>
</html>
22. <html>
<head>
<title>Second Page</title>
</head>
<body>
<?php
// view values in $_GET array
print_r($_GET);

// assign $_GET array values to variables for easier use


$id = $_GET['id'];
$name = $_GET['name'];
echo "<br /><strong>" . $id . ": {$name}</strong>";
?>
</body>
</html>
23. <html>
<head>
<title>First Page</title>
</head>
<body>
<a href="secondpage.php?name=Habib&&id=42">Second Page</a>
</body>
</html>
24. <html>

PHP Lab Manual Prepared By Seid H. Page 17


<head>
<title>Cookies</title>
</head>
<body>

<?php // Setting a cookie

// setcookie(name, value, expiration);


setcookie('test', 45, time()+(60*60*24*7));
?>

</body>
</html>
25. <html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<?php // Reading the value of a cookie

// give $var1 a default value


$var1 = 0;
// if cookie with name 'test' exists then set $var1 to its value
if (isset($_COOKIE['test'])) {
$var1 = $_COOKIE['test'];
}
echo $var1;
?>

<?php // Deleting a cookie

// set cookie value to 0 and expiration to the distant past


setcookie('test', 0, time()-(60*60*24*7));
?>

</body>
</html>
26. <html>
<head>
<title>Form Processing</title>
</head>
<body>
<?php
// Ultra-simple form processing
// Just retrieve the value and return it to the browser

PHP Lab Manual Prepared By Seid H. Page 18


$username = $_POST['username'];
$password = $_POST['password'];

echo "{$username}: {$password}";


?>
</body>
</html>
27. <html>
<head>
<title>Forms</title>
</head>
<body>
<form action="process.php" method="post">
Username: <input type="text" name="username" value="" />
<br />
Password: <input type="password" name="password" value="" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
28. <?php
session_start();
/* session_start() MUST be called before creating, accessing or deleting a
session
session_start() MUST be called before any white space or HTML is output
to the browser (unless output buffering has been turned on).
Says to PHP: get the session cookie from the browser and open up that file
for use
or if no session cookie was found, or no file that matches, create a
new one
*/
?>
<html>
<head>
<title>Sessions</title>
</head>
<body>
<?php
// since a session has been started above, it's available and ready
for use

// set values in the session


$_SESSION['first_name'] = "kevin";
$_SESSION['last_name'] = "skoglund";
?>

PHP Lab Manual Prepared By Seid H. Page 19


<?php

// read values from the session


$name = $_SESSION['first_name'] . " " .
$_SESSION['last_name'];
echo $name;
?>
</body>
</html>
29. <?php
// This is how you redirect a page (aka "302 redirect")
header("Location: basic.html");
exit;

// Always use exit to keep anything else from the page from executing

/* header() must come before any whitespace or HTML is output


to the browser unless output buffering is turned on.
Only 1 header can be sent; if HTML has been sent, then the header already
went too.
*/
?>
<?php
// This is how you return a 404 error (or another response code)

// header("HTTP/1.0 404 Not Found");


// exit;
?>
<html>
<head>
<title>Headers</title>
</head>
<body>

</body>
</html>
30. <html>
<head>
<title>Include</title>
</head>
<body>
<?php
// inserts the contents of the file "included_func.php" as if
// those same lines had been typed here.
include("included_func.php");

PHP Lab Manual Prepared By Seid H. Page 20


?>

<?php hello("Everyone"); ?>

<?php
/* In addition to include(), you can also use:
include_once();
require();
require_once();

include_once and require_once will include a file UNLESS it


has already been included (PHP keeps track).
Useful for files with constants & functions because
they can't be defined more than once.
*/
?>
</body>
</html>
31. <?php // This file is being included by includes.php

function hello($name) {
echo "Hello {$name}!";
}

/* Note: Even though the request to include this file was inside php-tags,
the file needs to have php-tags around any PHP.
PHP always assumes HTML unless told differently by those tags.
*/
?>
32. <?php //The calendar form
define("ADAY", (60*60*24));
if ((!isset($_POST["month"])) || (!isset($_POST["year"]))) {
$nowArray = getdate();
$month = $nowArray["mon"];
$year = $nowArray["year"];
} else {
$month = $_POST["month"];
$year = $_POST["year"];
}
$start = mktime (12, 0, 0, $month, 1, $year);
$firstDayArray = getdate($start);
?>
<html>
<head>
<title><?php echo "Calendar: ".$firstDayArray["month"]."
".$firstDayArray["year"]; ?></title>

PHP Lab Manual Prepared By Seid H. Page 21


<head>
<body>
<h1>Select a Month/Year Combination</h1>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<select name="month">
<?php
$months = Array("January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December");
for ($x=1; $x <= count($months); $x++) {
echo "<option value=\"$x\"";
if ($x == $month) {
echo " selected";
}
echo ">".$months[$x-1]."</option>";
}
?>
</select>
<select name="year">
<?php
for ($x=1990; $x<=2015; $x++) {
echo "<option";
if ($x == $year) {
echo " selected";
}
echo ">$x</option>";
}
?>
</select>
<input type="submit" value="Go!">
</form>
<br/>
<?php
$days = Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
echo "<table border=\"1\" cellpadding=\"5\"><tr>\n";
foreach ($days as $day) {
echo "<td style=\"background-color: #CCCCCC;
text-align: center;width: 14%\"><strong>$day</strong></td>\n";
}
for ($count=0; $count < (6*7); $count++) {
$dayArray = getdate($start);
if (($count % 7) == 0) {
if ($dayArray["mon"] != $month) {
break;
} else {
echo "</tr><tr>\n";
}

PHP Lab Manual Prepared By Seid H. Page 22


}
if ($count < $firstDayArray["wday"] || $dayArray["mon"] != $month) {
echo "<td>&nbsp;</td>\n";
} else {
echo "<td>".$dayArray["mday"]." &nbsp;&nbsp; </td>\n";
$start += ADAY;
}
}
echo "</tr></table>";
?>
</body>
</html>
33. <?php
// Five steps to PHP database connections:

// 1. Create a database connection


// (Use your own servername, username and password if they are
different.)
// $connection allows us to keep refering to this connection after it is
established
$connection = mysql_connect("localhost","root","OtlPHP07");
if (!$connection) {
die("Database connection failed: " . mysql_error());
}

// 2. Select a database to use


$db_select = mysql_select_db("widget_corp",$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}

?>
<html>
<head>
<title>Databases</title>
</head>
<body>
<?php
// 3. Perform database query
$result = mysql_query("SELECT * FROM subjects", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}

// 4. Use returned data


while ($row = mysql_fetch_array($result)) {

PHP Lab Manual Prepared By Seid H. Page 23


echo $row["menu_name"]." ".$row["position"]."<br />";
}

?>
</body>
</html>
<?php
// 5. Close connection
mysql_close($connection);
?>
34. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
if (isset($_GET['subj'])) {
$sel_subj = $_GET['subj'];
$sel_page = "";
} elseif (isset($_GET['page'])) {
$sel_subj = "";
$sel_page = $_GET['page'];
} else {
$sel_subj = "";
$sel_page = "";
}
?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<ul class="subjects">
<?php
$subject_set = get_all_subjects();
while ($subject = mysql_fetch_array($subject_set)) {
echo "<li";
if ($subject["id"] == $sel_subj) { echo " class=\"selected\""; }
echo "><a href=\"content.php?subj=" . urlencode($subject["id"]) .
"\">{$subject["menu_name"]}</a></li>";
$page_set = get_pages_for_subject($subject["id"]);
echo "<ul class=\"pages\">";
while ($page = mysql_fetch_array($page_set)) {
echo "<li";
if ($page["id"] == $sel_page) { echo " class=\"selected\"";
}
echo "><a href=\"content.php?page=" .
urlencode($page["id"]) .
"\">{$page["menu_name"]}</a></li>";
}

PHP Lab Manual Prepared By Seid H. Page 24


echo "</ul>";
}

?>
</ul>
</td>
<td id="page">
<h2>Content Area</h2>
<?php echo $sel_subj; ?><br />
<?php echo $sel_page; ?><br />
</td>
</tr>
</table>
<?php require("includes/footer.php"); ?>
35. <?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
&nbsp;
</td>
<td id="page">
<h2>Staff Menu</h2>
<p>Welcome to the staff area.</p>
<ul>
<li><a href="content.php">Manage Website
Content</a></li>
<li><a href="new_user.php">Add Staff User</a></li>
<li><a href="logout.php">Logout</a></li>
</ul>
</td>
</tr>
</table>
<?php include("includes/footer.php"); ?>
36. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
find_selected_page();
?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">

PHP Lab Manual Prepared By Seid H. Page 25


</td>
</tr>
</table>
<?php require("includes/footer.php"); ?>
37. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php find_selected_page(); ?>

<?php include("includes/header.php"); ?>


<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<h2>Add Subject</h2>
<form action="create_subject.php" method="post">
<p>Subject name:
<input type="text" name="menu_name" value=""
id="menu_name" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = get_all_subjects();
$subject_count =
mysql_num_rows($subject_set);
// $subject_count + 1 b/c we are
adding a subject
for($count=1; $count <=
$subject_count+1; $count++) {
echo "<option
value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" />
No
&nbsp;
<input type="radio" name="visible" value="1" />
Yes
</p>
<input type="submit" value="Add Subject" />
</form>

PHP Lab Manual Prepared By Seid H. Page 26


<br />
<a href="content.php">Cancel</a>
</td>
</tr>
</table>
<?php require("includes/footer.php"); ?>
38. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>

<?php
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
?>
<?php
$query = "INSERT INTO subjects (
menu_name, position, visible
) VALUES (
'{$menu_name}', {$position}, {$visible}
)";
$result = mysql_query($query, $connection);
if ($result) {
// Success!
header("Location: content.php");
exit;
} else {
// Display error message.
echo "<p>Subject creation failed.</p>";
echo "<p>" . mysql_error() . "</p>";
}
?>

<?php mysql_close($connection); ?>


39. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php find_selected_page(); ?>

<?php include("includes/header.php"); ?>


<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<h2>Edit Subject: <?php echo $sel_subject['menu_name'];
?></h2>

PHP Lab Manual Prepared By Seid H. Page 27


<form action="edit_subject.php?subj=<?php echo
urlencode($sel_subject['id']); ?>" method="post">
<p>Subject name:
<input type="text" name="menu_name" value=""
id="menu_name" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = get_all_subjects();
$subject_count =
mysql_num_rows($subject_set);
// $subject_count + 1 b/c we are
adding a subject
for($count=1; $count <=
$subject_count+1; $count++) {
echo "<option
value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" />
No
&nbsp;
<input type="radio" name="visible" value="1" />
Yes
</p>
<input type="submit" value="Add Subject" />
</form>
<br />
<a href="content.php">Cancel</a>
</td>
</tr>
</table>
<?php require("includes/footer.php"); ?>
40. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php find_selected_page(); ?>
<?php
if (intval($_GET['id']) == 0) {
redirect_to('content.php');
}
if (isset($_POST['submit'])) {
$errors = array();

PHP Lab Manual Prepared By Seid H. Page 28


// Form Validation
$required_fields = array('menu_name', 'position', 'visible');
foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) ||
empty($_POST[$fieldname])) {
$errors[] = $fieldname;
}
}
$fields_with_lengths = array('menu_name' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) >
$maxlength) { $errors[] = $fieldname; }
}

$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);

}
?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<h2>Edit Subject: <?php echo $sel_subject['menu_name'];
?></h2>
<form action="edit_subject.php?subj=<?php echo
urlencode($sel_subject['id']); ?>" method="post">
<p>Subject name:
<input type="text" name="menu_name"
value="<?php echo $sel_subject['menu_name']; ?>" id="menu_name" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = get_all_subjects();
$subject_count =
mysql_num_rows($subject_set);
// $subject_count + 1 b/c we are
adding a subject

PHP Lab Manual Prepared By Seid H. Page 29


for($count=1; $count <=
$subject_count+1; $count++) {
echo "<option
value=\"{$count}\"";
if ($sel_subject['position'] ==
$count) {
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible"
value="0"<?php
if ($sel_subject['visible'] == 0) { echo " checked"; }
?> /> No
&nbsp;
<input type="radio" name="visible"
value="1"<?php
if ($sel_subject['visible'] == 1) { echo " checked"; }
?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject"
/>
</form>
<br />
<a href="content.php">Cancel</a>
</td>
</tr>
</table>
<?php require("includes/footer.php"); ?>
41. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
if (intval($_GET['subj']) == 0) {
redirect_to("content.php");
}
if (isset($_POST['submit'])) {
$errors = array();

$required_fields = array('menu_name', 'position', 'visible');


foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) ||
empty($_POST[$fieldname])) {

PHP Lab Manual Prepared By Seid H. Page 30


$errors[] = $fieldname;
}
}
$fields_with_lengths = array('menu_name' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) >
$maxlength) { $errors[] = $fieldname; }
}

if (empty($errors)) {
// Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);

$query = "UPDATE subjects SET


menu_name = '{$menu_name}',
position = {$position},
visible = {$visible}
WHERE id = {$id}";
$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
// Success
} else {
// Failed
}

} else {
// Errors occurred
}

} // end: if (isset($_POST['submit']))
?>
<?php find_selected_page(); ?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">

PHP Lab Manual Prepared By Seid H. Page 31


<h2>Edit Subject: <?php echo $sel_subject['menu_name'];
?></h2>
<form action="edit_subject.php?subj=<?php echo
urlencode($sel_subject['id']); ?>" method="post">
<p>Subject name:
<input type="text" name="menu_name"
value="<?php echo $sel_subject['menu_name']; ?>" id="menu_name" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = get_all_subjects();
$subject_count =
mysql_num_rows($subject_set);
// $subject_count + 1 b/c we are
adding a subject
for($count=1; $count <=
$subject_count+1; $count++) {
echo "<option
value=\"{$count}\"";
if ($sel_subject['position'] ==
$count) {
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible"
value="0"<?php
if ($sel_subject['visible'] == 0) { echo " checked"; }
?> /> No
&nbsp;
<input type="radio" name="visible"
value="1"<?php
if ($sel_subject['visible'] == 1) { echo " checked"; }
?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject"
/>
</form>
<br />
<a href="content.php">Cancel</a>
</td>

PHP Lab Manual Prepared By Seid H. Page 32


</tr>
</table>
<?php require("includes/footer.php"); ?>
42. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
if (intval($_GET['subj']) == 0) {
redirect_to("content.php");
}
if (isset($_POST['submit'])) {
$errors = array();

$required_fields = array('menu_name', 'position', 'visible');


foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) ||
empty($_POST[$fieldname])) {
$errors[] = $fieldname;
}
}
$fields_with_lengths = array('menu_name' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) >
$maxlength) { $errors[] = $fieldname; }
}

if (empty($errors)) {
// Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);

$query = "UPDATE subjects SET


menu_name = '{$menu_name}',
position = {$position},
visible = {$visible}
WHERE id = {$id}";
$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
// Success
$message = "The subject was successfully
updated.";
} else {
// Failed
$message = "The subject update failed.";
$message .= "<br />". mysql_error();

PHP Lab Manual Prepared By Seid H. Page 33


}

} else {
// Errors occurred
$message = "There were " . count($errors) . " errors in the
form.";
}

} // end: if (isset($_POST['submit']))
?>
<?php find_selected_page(); ?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<h2>Edit Subject: <?php echo $sel_subject['menu_name'];
?></h2>
<?php if (!empty($message)) {
echo "<p class=\"message\">" . $message . "</p>";
} ?>
<?php
// output a list of the fields that had errors
if (!empty($errors)) {
echo "<p class=\"errors\">";
echo "Please review the following fields:<br />";
foreach($errors as $error) {
echo " - " . $error . "<br />";
}
echo "</p>";
}
?>
<form action="edit_subject.php?subj=<?php echo
urlencode($sel_subject['id']); ?>" method="post">
<p>Subject name:
<input type="text" name="menu_name"
value="<?php echo $sel_subject['menu_name']; ?>" id="menu_name" />
</p>
<p>Position:
<select name="position">
<?php

PHP Lab Manual Prepared By Seid H. Page 34


$subject_set = get_all_subjects();
$subject_count =
mysql_num_rows($subject_set);
// $subject_count + 1 b/c we are
adding a subject
for($count=1; $count <=
$subject_count+1; $count++) {
echo "<option
value=\"{$count}\"";
if ($sel_subject['position'] ==
$count) {
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible"
value="0"<?php
if ($sel_subject['visible'] == 0) { echo " checked"; }
?> /> No
&nbsp;
<input type="radio" name="visible"
value="1"<?php
if ($sel_subject['visible'] == 1) { echo " checked"; }
?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject"
/>
</form>
<br />
<a href="content.php">Cancel</a>
</td>
</tr>
</table>
<?php require("includes/footer.php"); ?>
43. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
if (intval($_GET['subj']) == 0) {
redirect_to("content.php");
}
if (isset($_POST['submit'])) {
$errors = array();

PHP Lab Manual Prepared By Seid H. Page 35


$required_fields = array('menu_name', 'position', 'visible');
foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) ||
empty($_POST[$fieldname])) {
$errors[] = $fieldname;
}
}
$fields_with_lengths = array('menu_name' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength ) {
if (strlen(trim(mysql_prep($_POST[$fieldname]))) >
$maxlength) { $errors[] = $fieldname; }
}

if (empty($errors)) {
// Perform Update
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);

$query = "UPDATE subjects SET


menu_name = '{$menu_name}',
position = {$position},
visible = {$visible}
WHERE id = {$id}";
$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
// Success
$message = "The subject was successfully
updated.";
} else {
// Failed
$message = "The subject update failed.";
$message .= "<br />". mysql_error();
}

} else {
// Errors occurred
$message = "There were " . count($errors) . " errors in the
form.";
}

PHP Lab Manual Prepared By Seid H. Page 36


} // end: if (isset($_POST['submit']))
?>
<?php find_selected_page(); ?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<h2>Edit Subject: <?php echo $sel_subject['menu_name'];
?></h2>
<?php if (!empty($message)) {
echo "<p class=\"message\">" . $message . "</p>";
} ?>
<?php
// output a list of the fields that had errors
if (!empty($errors)) {
echo "<p class=\"errors\">";
echo "Please review the following fields:<br />";
foreach($errors as $error) {
echo " - " . $error . "<br />";
}
echo "</p>";
}
?>
<form action="edit_subject.php?subj=<?php echo
urlencode($sel_subject['id']); ?>" method="post">
<p>Subject name:
<input type="text" name="menu_name"
value="<?php echo $sel_subject['menu_name']; ?>" id="menu_name" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = get_all_subjects();
$subject_count =
mysql_num_rows($subject_set);
// $subject_count + 1 b/c we are
adding a subject
for($count=1; $count <=
$subject_count+1; $count++) {
echo "<option
value=\"{$count}\"";
if ($sel_subject['position'] ==
$count) {

PHP Lab Manual Prepared By Seid H. Page 37


echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible"
value="0"<?php
if ($sel_subject['visible'] == 0) { echo " checked"; }
?> /> No
&nbsp;
<input type="radio" name="visible"
value="1"<?php
if ($sel_subject['visible'] == 1) { echo " checked"; }
?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject"
/>
&nbsp;&nbsp;
<a href="delete_subject.php?subj=<?php echo
urlencode($sel_subject['id']); ?>" onclick="return confirm('Are you sure?');">Delete
Subject</a>
</form>
<br />
<a href="content.php">Cancel</a>
</td>
</tr>
</table>
<?php require("includes/footer.php"); ?>
44. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
if (intval($_GET['subj']) == 0) {
redirect_to("content.php");
}

$id = mysql_prep($_GET['subj']);

if ($subject = get_subject_by_id($id)) {

$query = "DELETE FROM subjects WHERE id = {$id} LIMIT 1";


$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
redirect_to("content.php");

PHP Lab Manual Prepared By Seid H. Page 38


} else {
// Deletion Failed
echo "<p>Subject deletion failed.</p>";
echo "<p>" . mysql_error() . "</p>";
echo "<a href=\"content.php\">Return to Main Page</a>";
}
} else {
// subject didn't exist in database
redirect_to("content.php");
}
?>

<?php mysql_close($connection); ?>


45. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
// make sure the subject id sent is an integer
if (intval($_GET['page']) == 0) {
redirect_to('content.php');
}

$id = mysql_prep($_GET['page']);
// make sure the page exists (not strictly necessary)
// it gives some extra security and allows use of
// the page's subject_id for the redirect
if ($page = get_page_by_id($id)) {
// LIMIT 1 isn't necessary but is a good fail safe
$query = "DELETE FROM pages WHERE id = {$page['id']} LIMIT 1";
$result = mysql_query ($query);
if (mysql_affected_rows() == 1) {
// Successfully deleted
redirect_to("edit_subject.php?subj={$page['subject_id']}");
} else {
// Deletion failed
echo "<p>Page deletion failed.</p>";
echo "<p>" . mysql_error() . "</p>";
echo "<a href=\"content.php\">Return to Main Site</a>";
}
} else {
// page didn't exist, deletion was not attempted
redirect_to('content.php');
}
?>
<?php
// because this file didn't include footer.php we need to add this manually
mysql_close($db);

PHP Lab Manual Prepared By Seid H. Page 39


?>
46. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>

<?php find_selected_page(); ?>


<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo public_navigation($sel_subject, $sel_page); ?>
</td>
<td id="page">
<?php if ($sel_page) { ?>
<h2><?php echo htmlentities($sel_page['menu_name']);
?></h2>
<div class="page-content">
<?php echo strip_tags(nl2br($sel_page['content']),
"<b><br><p><a>"); ?>
</div>
<?php } else { ?>
<h2>Welcome to Widget Corp</h2>
<?php } ?>
</td>
</tr>
</table>
<?php include("includes/footer.php"); ?>
47. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
// make sure the subject id sent is an integer
if (intval($_GET['page']) == 0) {
redirect_to('content.php');
}

include_once("includes/form_functions.php");

// START FORM PROCESSING


// only execute the form processing if the form has been submitted
if (isset($_POST['submit'])) {
// initialize an array to hold our errors
$errors = array();

// perform validations on the form data


$required_fields = array('menu_name', 'position', 'visible', 'content');
$errors = array_merge($errors, check_required_fields($required_fields));

PHP Lab Manual Prepared By Seid H. Page 40


$fields_with_lengths = array('menu_name' => 30);
$errors = array_merge($errors,
check_max_field_lengths($fields_with_lengths));

// clean up the form data before putting it in the database


$id = mysql_prep($_GET['page']);
$menu_name = trim(mysql_prep($_POST['menu_name']));
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$content = mysql_prep($_POST['content']);

// Database submission only proceeds if there were NO errors.


if (empty($errors)) {
$query = "UPDATE pages SET
menu_name = '{$menu_name}',
position = {$position},
visible = {$visible},
content = '{$content}'
WHERE id = {$id}";
$result = mysql_query($query);
// test to see if the update occurred
if (mysql_affected_rows() == 1) {
// Success!
$message = "The page was successfully updated.";
} else {
$message = "The page could not be updated.";
$message .= "<br />" . mysql_error();
}
} else {
if (count($errors) == 1) {
$message = "There was 1 error in the form.";
} else {
$message = "There were " . count($errors) . " errors in the
form.";
}
}
// END FORM PROCESSING
}
?>
<?php find_selected_page(); ?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($sel_subject, $sel_page); ?>
<br />

PHP Lab Manual Prepared By Seid H. Page 41


<a href="new_subject.php">+ Add a new subject</a>
</td>
<td id="page">
<h2>Edit page: <?php echo $sel_page['menu_name']; ?></h2>
<?php if (!empty($message)) {echo "<p class=\"message\">" .
$message . "</p>";} ?>
<?php if (!empty($errors)) { display_errors($errors); } ?>

<form action="edit_page.php?page=<?php echo $sel_page['id'];


?>" method="post">
<?php include "page_form.php" ?>
<input type="submit" name="submit" value="Update
Page" />&nbsp;&nbsp;
<a href="delete_page.php?page=<?php echo
$sel_page['id']; ?>" onclick="return confirm('Are you sure you want to delete this
page?');">Delete page</a>
</form>
<br />
<a href="content.php?page=<?php echo $sel_page['id'];
?>">Cancel</a><br />
</td>
</tr>
</table>
<?php include("includes/footer.php"); ?>
48. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
// make sure the subject id sent is an integer
if (intval($_GET['subj']) == 0) {
redirect_to('content.php');
}

include_once("includes/form_functions.php");

// START FORM PROCESSING


// only execute the form processing if the form has been submitted
if (isset($_POST['submit'])) {
// initialize an array to hold our errors
$errors = array();

// perform validations on the form data


$required_fields = array('menu_name', 'position', 'visible', 'content');
$errors = array_merge($errors, check_required_fields($required_fields,
$_POST));

$fields_with_lengths = array('menu_name' => 30);

PHP Lab Manual Prepared By Seid H. Page 42


$errors = array_merge($errors,
check_max_field_lengths($fields_with_lengths, $_POST));

// clean up the form data before putting it in the database


$subject_id = mysql_prep($_GET['subj']);
$menu_name = trim(mysql_prep($_POST['menu_name']));
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$content = mysql_prep($_POST['content']);

// Database submission only proceeds if there were NO errors.


if (empty($errors)) {
$query = "INSERT INTO pages (
menu_name, position, visible, content,
subject_id
) VALUES (
'{$menu_name}', {$position}, {$visible},
'{$content}', {$subject_id}
)";
if ($result = mysql_query($query, $connection)) {
// as is, $message will still be discarded on the redirect
$message = "The page was successfully created.";
// get the last id inserted over the current db connection
$new_page_id = mysql_insert_id();
redirect_to("content.php?page={$new_page_id}");
} else {
$message = "The page could not be created.";
$message .= "<br />" . mysql_error();
}
} else {
if (count($errors) == 1) {
$message = "There was 1 error in the form.";
} else {
$message = "There were " . count($errors) . " errors in the
form.";
}
}
// END FORM PROCESSING
}
?>
<?php find_selected_page(); ?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">

PHP Lab Manual Prepared By Seid H. Page 43


<?php echo navigation($sel_subject, $sel_page, $public = false);
?>
<br />
<a href="new_subject.php">+ Add a new subject</a>
</td>
<td id="page">
<h2>Adding New Page</h2>
<?php if (!empty($message)) {echo "<p class=\"message\">" .
$message . "</p>";} ?>
<?php if (!empty($errors)) { display_errors($errors); } ?>

<form action="new_page.php?subj=<?php echo $sel_subject['id'];


?>" method="post">
<?php $new_page = true; ?>
<?php include "page_form.php" ?>
<input type="submit" name="submit" value="Create Page"
/>
</form>
<br />
<a href="edit_subject.php?subj=<?php echo $sel_subject['id'];
?>">Cancel</a><br />
</td>
</tr>
</table>
<?php include("includes/footer.php"); ?>
49. <?php // this page is included by new_page.php and edit_page.php ?>
<?php if (!isset($new_page)) {$new_page = false;} ?>

<p>Page name: <input type="text" name="menu_name" value="<?php echo


$sel_page['menu_name']; ?>" id="menu_name" /></p>

<p>Position: <select name="position">


<?php
if (!$new_page) {
$page_set = get_pages_for_subject($sel_page['subject_id']);
$page_count = mysql_num_rows($page_set);
} else {
$page_set = get_pages_for_subject($sel_subject['id']);
$page_count = mysql_num_rows($page_set) + 1;
}
for ($count=1; $count <= $page_count; $count++) {
echo "<option value=\"{$count}\"";
if ($sel_page['position'] == $count) { echo " selected"; }
echo ">{$count}</option>";
}
?>

PHP Lab Manual Prepared By Seid H. Page 44


</select></p>
<p>Visible:
<input type="radio" name="visible" value="0"<?php
if ($sel_page['visible'] == 0) { echo " checked"; }
?> /> No
&nbsp;
<input type="radio" name="visible" value="1"<?php
if ($sel_page['visible'] == 1) { echo " checked"; }
?> /> Yes
</p>
<p>Content:<br />
<textarea name="content" rows="20" cols="80"><?php echo $sel_page['content'];
?></textarea>
</p>
50. <?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php

if (logged_in()) {
redirect_to("staff.php");
}

include_once("includes/form_functions.php");

// START FORM PROCESSING


if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();

// perform validations on the form data


$required_fields = array('username', 'password');
$errors = array_merge($errors, check_required_fields($required_fields,
$_POST));

$fields_with_lengths = array('username' => 30, 'password' => 30);


$errors = array_merge($errors,
check_max_field_lengths($fields_with_lengths, $_POST));

$username = trim(mysql_prep($_POST['username']));
$password = trim(mysql_prep($_POST['password']));
$hashed_password = sha1($password);

if ( empty($errors) ) {
// Check database to see if username and the hashed password exist
there.
$query = "SELECT id, username ";

PHP Lab Manual Prepared By Seid H. Page 45


$query .= "FROM users ";
$query .= "WHERE username = '{$username}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "LIMIT 1";
$result_set = mysql_query($query);
confirm_query($result_set);
if (mysql_num_rows($result_set) == 1) {
// username/password authenticated
// and only 1 match
$found_user = mysql_fetch_array($result_set);
$_SESSION['user_id'] = $found_user['id'];
$_SESSION['username'] = $found_user['username'];

redirect_to("staff.php");
} else {
// username/password combo was not found in the database
$message = "Username/password combination
incorrect.<br />
Please make sure your caps lock key is off and try
again.";
}
} else {
if (count($errors) == 1) {
$message = "There was 1 error in the form.";
} else {
$message = "There were " . count($errors) . " errors in the
form.";
}
}

} else { // Form has not been submitted.


if (isset($_GET['logout']) && $_GET['logout'] == 1) {
$message = "You are now logged out.";
}
$username = "";
$password = "";
}
?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<a href="index.php">Return to public site</a>
</td>
<td id="page">
<h2>Staff Login</h2>

PHP Lab Manual Prepared By Seid H. Page 46


<?php if (!empty($message)) {echo "<p class=\"message\">" .
$message . "</p>";} ?>
<?php if (!empty($errors)) { display_errors($errors); } ?>
<form action="login.php" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username"
maxlength="30" value="<?php echo htmlentities($username); ?>" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"
maxlength="30" value="<?php echo htmlentities($password); ?>" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
name="submit" value="Login" /></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
<?php include("includes/footer.php"); ?>
51. <?php require_once("includes/functions.php"); ?>
<?php
// Four steps to closing a session
// (i.e. logging out)

// 1. Find the session


session_start();

// 2. Unset all the session variables


$_SESSION = array();

// 3. Destroy the session cookie


if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}

// 4. Destroy the session


session_destroy();

redirect_to("login.php?logout=1");

PHP Lab Manual Prepared By Seid H. Page 47


52. <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
include_once("includes/form_functions.php");

// START FORM PROCESSING


if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();

// perform validations on the form data


$required_fields = array('username', 'password');
$errors = array_merge($errors, check_required_fields($required_fields,
$_POST));

$fields_with_lengths = array('username' => 30, 'password' => 30);


$errors = array_merge($errors,
check_max_field_lengths($fields_with_lengths, $_POST));

$username = trim(mysql_prep($_POST['username']));
$password = trim(mysql_prep($_POST['password']));
$hashed_password = sha1($password);

if ( empty($errors) ) {
$query = "INSERT INTO users (
username, hashed_password
) VALUES (
'{$username}',
'{$hashed_password}'
)";
$result = mysql_query($query, $connection);
if ($result) {
$message = "The user was successfully created.";
} else {
$message = "The user could not be created.";
$message .= "<br />" . mysql_error();
}
} else {
if (count($errors) == 1) {
$message = "There was 1 error in the form.";
} else {
$message = "There were " . count($errors) . " errors in the
form.";
}
}
} else { // Form has not been submitted.
$username = "";

PHP Lab Manual Prepared By Seid H. Page 48


$password = "";
}
?>
<?php include("includes/header.php"); ?>
<table id="structure">
<tr>
<td id="navigation">
<a href="staff.php">Return to Menu</a><br />
<br />
</td>
<td id="page">
<h2>Create New User</h2>
<?php if (!empty($message)) {echo "<p class=\"message\">" .
$message . "</p>";} ?>
<?php if (!empty($errors)) { display_errors($errors); } ?>
<form action="new_user.php" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username"
maxlength="30" value="<?php echo htmlentities($username); ?>" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"
maxlength="30" value="<?php echo htmlentities($password); ?>" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
name="submit" value="Create user" /></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
<?php include("includes/footer.php"); ?>
?>

PHP Lab Manual Prepared By Seid H. Page 49

You might also like