Webocreation

Sunday, February 14, 2010

Code to insert check box elements in the database

Code to insert check box elements in the database
<?php

if(isset($_POST['button']))
{


//count-counts varibale in array
$num=count($_POST['hobbies']);

$errors=array();


$total_hobbies="";


for($i=0;$i<$num;$i++)
{
$total_hobbies=$total_hobbies.$_POST['hobbies'][$i].",";
}

$total_hobbies = substr($total_hobbies, 0,-1); // returns "ef"
//echo $total_hobbies;

if(empty($_POST['name']))
{
$errors[]="Your Name field is empty.Please fill it";
}
else
{
$name=$_POST['name'];
}

if(empty($_POST['address']))
{
$errors[]="Your address field is empty.Please fill it";
}
else
{
$address=$_POST['address'];
}


if(empty($_POST['user_name']))
{
$errors[]="Your user_name field is empty.Please fill it";
$user_name=FALSE;
}
else
{
$user_name=$_POST['user_name'];
}


$education=$_POST['education'];

$gender=$_POST['gender'];


if(strlen($_POST['pass'])<4)
{
$errors[]="Password field cannot be less than 4 character.Please fill it";
}
else
{
$pass=$_POST['pass'];
}



if (empty($errors))
{
require_once('connect.php');
//echo "$name $address $user_name $pass";


$query1="select user_id from profile where user_name=\"$user_name\"";

$result1=mysql_query($query1);
if(mysql_num_rows($result1)>0)
{
echo "This username is not available";
}
else
{


$query="insert into profile(name,address,user_name,pass,added_on) values ('$name','$address','$user_name',MD5('$pass'),NOW())";
//echo $query;

$result=mysql_query($query);

if (mysql_affected_rows()==1)
{
echo "You Are registered";

$id=mysql_insert_id();//gives last inserted id which is useful auto increment

if($_FILES['photo']['type']=='image/jpeg' or $_FILES['photo']['type']=='image/pjpeg')
{
$ext=".jpg";
}
else if ($_FILES['photo']['type']=='image/gif')
{
$ext=".gif";
}
else
{
echo "This image format is not allowed";
}

$file_name=$id.$ext;//7.jpg
$file_name1="tb".$id.$ext;//7.jpg
$query12="update profile set image='$file_name' where user_id=$id";
mysql_query($query12);//for image as image id is not initially known which is required to make file name



if (copy($_FILES['photo']['tmp_name'],"images/$file_name"))
{
echo "File Uploaded";


$sizes = getimagesize("images/$file_name");
//give image width and height//0-width 1 heigh

$thumb = imagecreatetruecolor(100, 100);//creates empty canvas
$source = imagecreatefromjpeg("images/$file_name");//this is source

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, 100, 100, $sizes[0], $sizes[1]);

// Output
//imagejpeg($thumb);
imagejpeg($thumb,"images/$file_name1");



/*$thumb1 = imagecreatetruecolor(400, 400);//creates empty canvas
$source1 = imagecreatefromjpeg("images/$file_name");//this is source

// Resize
imagecopyresized($thumb1, $source1, 0, 0, 0, 0, 400, 400, $sizes[0], $sizes[1]);

// Output
//imagejpeg($thumb);
imagejpeg($thumb1,"images/$file_name");*/


}
else
{
echo "File could not be uploaded";
}



}
else
{
echo "You Are NOT registered";
}
}




}

else
{

$errors_num=count($errors);
for($i=0;$i<$errors_num;$i++)
{
echo "{$errors[$i]}<br/>";
}
}


}//end of submit






?>





<form action="register.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>Name
<label>
<input type="text" name="name" id="name" />
</label>
</p>
<p>Address
<input type="text" name="address" id="address" />
</p>

<p>Education
<label>
<select name="education">
<option value="1">Under Slc</option>
<option value="2">Intermediate</option>
<option value="3">Above Intermediate</option>
</select>
</label>
</p>

<p>Gender:
<label>
<input type="radio" name="gender" value="1" checked="checked"/>
Male</label>
<label>
<input type="radio" name="gender" value="2"/>
Female</label>
<br />
</p>
<p>Hobbies
<label>
<input type="checkbox" name="hobbies[]" value="playing" />
Playing</label>
<label>
<input type="checkbox" name="hobbies[]" value="Singing" />
Singing</label>
<br />
</p>
<p>Image
<label>
<input type="file" name="photo" />
</label>
</p>
<p>Username
<input type="text" name="user_name" id="user_name" />
</p>
<p>Password
<input type="password" name="pass" id="pass" />
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>


<?php
/*
mysql_connect()//connects
mysql_select_db()//
mysql_query()//passes query to mysql from php/
//CUD-Create-Unpdate-Delete---
//R-Read
mysql_affected_rows
mysql_num_rows
mysql_fetch_array
*/


?>

Friday, February 12, 2010

Building a CMS with PHP Part 4 - Editing Posts


Building a CMS with PHP Part 4 - Editing Posts video download

Building a CMS with PHP and MYSQL Part 3


Building a CMS with PHP and MYSQL Part 3

Building a CMS with PHP and MYSQL Part 2


Building a CMS with PHP and MYSQL Pat 2 video, php tutorials video, php and mysql to make cms video

Creating a CMS with PHP and MYSQL


Creating a CMS with PHP and MYSQL, php video tutorial for making the Cms with php and mysql, Creating a CMS with PHP and MYSQL video, video to make site to edit, delete and update the contents

php video tutorial



php video, php tutorial video, php simple tutorials video, simple php video tutorials

Php and mysql free book download

Php Mysql

Download free php and mysql books

Php Mysql

definition of php function explode () function

<?php
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?>
Description
array explode ( string $delimiter , string $string [, int $limit ] )
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter .

DBA example in php

<?php

$id = dba_open("/tmp/test.db", "n", "db2");

if (!$id) {
echo "dba_open failed\n";
exit;
}

dba_replace("key", "This is an example!", $id);

if (dba_exists("key", $id)) {
echo dba_fetch("key", $id);
dba_delete("key", $id);
}

dba_close($id);
?>
DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.

All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().

You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.

Simple login using php

<?php

if(isset($_POST['button']))
{
$user_name=$_POST['user_name'];
$pass=$_POST['pass'];

include('connect.php');

//echo md5('pass');

$query1="select user_id from profile where user_name=\"$user_name\" and pass=MD5(\"$pass\")";
//echo $query1;
$result1=mysql_query($query1);
if(mysql_num_rows($result1)>0)
{
echo "You are logged in";
//redirect
//session start
}
else
{
echo "Wrong username and password please try again.";
}





}

?>


<form id="form1" name="form1" method="post" action="login.php">
<p>Username
<label>
<input type="text" name="user_name" id="textfield" />
</label>
</p>
<p>Password
<label>
<input type="password" name="pass" id="textfield2" />
</label>
</p>
<p>
<label>
<input type="submit" name="button" id="button" value="Login" />
</label>
</p>
</form>
Simple login using php

Upload your photo with php code

<?php

if(isset($_POST['button']))
{


//count-counts varibale in array
$num=count($_POST['hobbies']);

$errors=array();


$total_hobbies="";


for($i=0;$i<$num;$i++)
{
$total_hobbies=$total_hobbies.$_POST['hobbies'][$i].",";
}

$total_hobbies = substr($total_hobbies, 0,-1); // returns "ef"
//echo $total_hobbies;

if(empty($_POST['name']))
{
$errors[]="Your Name field is empty.Please fill it";
}
else
{
$name=$_POST['name'];
}

if(empty($_POST['address']))
{
$errors[]="Your address field is empty.Please fill it";
}
else
{
$address=$_POST['address'];
}


if(empty($_POST['user_name']))
{
$errors[]="Your user_name field is empty.Please fill it";
$user_name=FALSE;
}
else
{
$user_name=$_POST['user_name'];
}


$education=$_POST['education'];

$gender=$_POST['gender'];


if(strlen($_POST['pass'])<4)
{
$errors[]="Password field cannot be less than 4 character.Please fill it";
}
else
{
$pass=$_POST['pass'];
}



if (empty($errors))
{
require_once('connect.php');
//echo "$name $address $user_name $pass";


$query1="select user_id from profile where user_name=\"$user_name\"";

$result1=mysql_query($query1);
if(mysql_num_rows($result1)>0)
{
echo "This username is not available";
}
else
{


$query="insert into profile(name,address,user_name,pass,added_on) values ('$name','$address','$user_name',MD5('$pass'),NOW())";
//echo $query;

$result=mysql_query($query);

if (mysql_affected_rows()==1)
{
echo "You Are registered";

$id=mysql_insert_id();//gives last inserted id which is useful auto increment

if($_FILES['photo']['type']=='image/jpeg' or $_FILES['photo']['type']=='image/pjpeg')
{
$ext=".jpg";
}
else if ($_FILES['photo']['type']=='image/gif')
{
$ext=".gif";
}
else
{
echo "This image format is not allowed";
}

$file_name=$id.$ext;//7.jpg
$file_name1="tb".$id.$ext;//7.jpg
$query12="update profile set image='$file_name' where user_id=$id";
mysql_query($query12);//for image as image id is not initially known which is required to make file name



if (copy($_FILES['photo']['tmp_name'],"images/$file_name"))
{
echo "File Uploaded";


$sizes = getimagesize("images/$file_name");
//give image width and height//0-width 1 heigh

$thumb = imagecreatetruecolor(100, 100);//creates empty canvas
$source = imagecreatefromjpeg("images/$file_name");//this is source

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, 100, 100, $sizes[0], $sizes[1]);

// Output
//imagejpeg($thumb);
imagejpeg($thumb,"images/$file_name1");



/*$thumb1 = imagecreatetruecolor(400, 400);//creates empty canvas
$source1 = imagecreatefromjpeg("images/$file_name");//this is source

// Resize
imagecopyresized($thumb1, $source1, 0, 0, 0, 0, 400, 400, $sizes[0], $sizes[1]);

// Output
//imagejpeg($thumb);
imagejpeg($thumb1,"images/$file_name");*/


}
else
{
echo "File could not be uploaded";
}



}
else
{
echo "You Are NOT registered";
}
}




}

else
{

$errors_num=count($errors);
for($i=0;$i<$errors_num;$i++)
{
echo "{$errors[$i]}<br/>";
}
}


}//end of submit






?>





<form action="register.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>Name
<label>
<input type="text" name="name" id="name" />
</label>
</p>
<p>Address
<input type="text" name="address" id="address" />
</p>

<p>Education
<label>
<select name="education">
<option value="1">Under Slc</option>
<option value="2">Intermediate</option>
<option value="3">Above Intermediate</option>
</select>
</label>
</p>

<p>Gender:
<label>
<input type="radio" name="gender" value="1" checked="checked"/>
Male</label>
<label>
<input type="radio" name="gender" value="2"/>
Female</label>
<br />
</p>
<p>Hobbies
<label>
<input type="checkbox" name="hobbies[]" value="playing" />
Playing</label>
<label>
<input type="checkbox" name="hobbies[]" value="Singing" />
Singing</label>
<br />
</p>
<p>Image
<label>
<input type="file" name="photo" />
</label>
</p>
<p>Username
<input type="text" name="user_name" id="user_name" />
</p>
<p>Password
<input type="password" name="pass" id="pass" />
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>


<?php
/*
mysql_connect()//connects
mysql_select_db()//
mysql_query()//passes query to mysql from php/
//CUD-Create-Unpdate-Delete---
//R-Read
mysql_affected_rows
mysql_num_rows
mysql_fetch_array
*/


?>
Upload your photo with php code

Tuesday, February 9, 2010

Declaration, recommendation and acknowledgement for the summer project

POKHARA UNIVERSITY
Faculty of Management

Nobel College

Declaration




I hereby declare that the work reported in this project work on “Everest Bank Ltd.” submitted to Nobel College, Pokhara University is my original work done in the form of partial requirement for the degree of (BBA) under the supervision of Mr. Rabin Dahal, Principal of Nobel College and Mr. Dipesh Shrestha, coordinator of Nobel College.





………………………………

Rupak Nepali

Exam Roll No.:- 73401**

Date: May 24th, 2009


Faculty of Management Studies

POKHARA UNIVERSITY

RECOMMENDATION

This is to certify that the Summer Project Report

Submitted by:

Rupak Nepali

Entitled

 Financial Analysis

Of

Everest Bank Limited, Kathmandu

has been prepared as approved by this college. This summer project report is forwarded for examination.

Supervisors

112                                   
Rabin Dahal(Principal) 
Dipesh Shrestha(Coordinator)                                                          

         

                                                                                                

     Date:

ACKNOWLEDGEMENT

This summer project is basically prepared for Pokhara University school of Management in partial fulfillment of the requirement for the degree of Bachelor Administration. This project report is based on the Everest Bank Limited.
 This report has helped me to expand my knowledge on banking Sectors and various other activities related to banking system of Nepal. During my preparation of this report, many people have continuously helped me. I would like to express my gratitude towards Mr. Dipesh Shrestha (co-ordinator) and Mr.Sanjay Lama for their co-operation and support. I am heartly thankful to Mr. Dinesh Gajurel to provide me the required material.

 I had tried my best to minimize errors to the extent possible by consulting my various books, supervisors, colleagues and organization. I hope my hard work will be rewarded.
 I extend sincere gratitude and appreciation for generous and helpful comments and valuable information delivered for the preparation of the report to all the respected personnel.


Rupak Nepali
Exam Roll No.:- 73401**
Date: May 24th, 2009

Title Page of summer project


Untitled Document

A Report On Financial Analysis

of
EVEREST BANK LIMITED

Kathmandu

By:
Rupak Nepali

PU Reg. No.:- 2006-2-03-***

Exam Roll No.:- 734***


A Summer Project Report
Submitted to:
Nobel College

Faculty of Management

Pokhara University

In partial fulfillment of the requirements for the degree of
Bachelor of Computer Information System

Kathmandu, Nepal

2009


Search code part 3

<html>
<head>
<title>Search Test</title>
</head>
<body topmargin="0" leftmargin="0">
<form action="search.php" method="post">
Search Term <input type="text" name="searchterm"><br />
<input type="submit" value="Search">
</form>
</body>
</html>





<?php
/*set varibles from form */
$searchterm = $_POST['searchterm'];
trim ($searchterm);
/*check if search term was entered*/
if (!$searchterm){
echo 'Please enter a search term.';
}
/*add slashes to search term*/
if (!get_magic_quotes_gpc())
{
$searchterm = addslashes($searchterm);
}

/* connects to database */
@ $dbconn = new mysqli('host', 'username', 'password', 'database');
if (mysqli_connect_errno())
{
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
/*query the database*/
$query = "select * from tablename where tablerow like '%".$searchterm."%'";
$result = $dbconn->query($query);
/*number of rows found*/
$num_results = $result->num_rows;

echo '<p>Found: '.$num_results.'</p>';
/*loops through results*/
for ($i=0; $i <$num_results; $i++)
{
$num_found = $i + 1;
$row = $result->fetch_assoc();
echo "$num_found. ".($row['tablerow'])." <br />";
}
/*free database*/
$result->free();
$dbconn->close();
?>

Search code part 2

this code source...

<?php
/*set varibles from form */
$searchterm = $_POST['searchterm'];
Trim ($searchterm);
/*check if search term was entered*/
If (!$searchterm){
echo 'Please enter a search term.';
}
/*add slashes to search term*/
If (!get_magic_quotes_gpc())
{
$searchterm = addslashes($searchterm);
}

/* connects to database */
@ $dbconn = new mysqli('localhost', 'root', '', 'sample1');
If (mysqli_connect_errno())
{
Echo 'Error: Could not connect to database. Please try again later.';
Exit;
}
/*query the database*/
$query = "select * from sheet1 where IndexNo like '%".$searchterm."%'";
$result = $dbconn->query($query);
/*number of rows found*/
$num_results = $result->num_rows;

echo '<p>Found: '.$num_results.'</p>';
/*loops through results*/
For ($I=0; $I <$num_results; $I++)
{
$num_found = $I + 1;
$row = $result->fetch_assoc();
Echo "$num_found. ".($row['IndexNo'])." <br />";
Echo "<table border='1'>
<tr>
<th>IndexNo</th>
<th>Name</th>
<th>Marks</th>
<th>Rank</th>
</tr>";

echo "<tr>";
echo "<td>" . $row['IndexNo'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Marks'] . "</td>";
echo "<td>" . $row['Rank'] . "</td>";
Echo "</tr>";
}
Echo "</table>";
/*free database*/
$result->free();
$dbconn->close();
?>

Search code part 1

1st part

CREATE TABLE users (fname VARCHAR(30), lname VARCHAR(30), info BLOB);

INSERT INTO users VALUES ( "Jim", "Jones", "In his spare time Jim enjoys biking, eating pizza, and classical music" ), ( "Peggy", "Smith", "Peggy is a water sports enthusiast who also enjoys making soap and selling cheese" ),( "Maggie", "Martin", "Maggie loves to cook itallian food including spagetti and pizza" ),( "Tex", "Moncom", "Tex is the owner and operator of The Pizza Palace, a local hang out joint" )


2nd part

<h2>Search</h2>
<form name="search" method="post" action="<?=$PHP_SELF?>">
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="fname">First Name</option>
<Option VALUE="lname">Last Name</option>
<Option VALUE="info">Profile</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>


3rd part

<?
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo "<h2>Results</h2><p>";

//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}

// Otherwise we connect to our Database
mysql_connect("mysql.yourhost.com", "user_name", "password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());

// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);

//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM users WHERE upper($field) LIKE'%$find%'");

//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['fname'];
echo " ";
echo $result['lname'];
echo "<br>";
echo $result['info'];
echo "<br>";
echo "<br>";
}

//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}

//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>





4th part

Breaking the PHP Code Down - Part 1

if ($searching =="yes")

In our original HTML form, we had a hidden field that sets this variable to "yes" when submitted. This line checks for that. If the form has been submitted then it runs the PHP code, if not it just ignores the rest of the coding.

if ($find == "")

The next thing we check before we run the query is that they actually entered a search string. If they haven't, we prompt them to, and don't process any more of the code. If we didn't have this code, and they entered a blank result, it would simply return the entire database's contents.

After this check we connect to our database, but before we can search we need to filter.

$find = strtoupper($find)

This changes all of the characters of the search string to UPPER case. We will explain how this is useful later.

$find = strip_tags($find)

This takes out any code they may have tried to enter in to the search box.

$find = trim ($find)

And this takes out all the whitespace - for example if they accidently put a few spaces at the end of their query.




5th part


Breaking the PHP Code Down - Part 2

$data = mysql_query("SELECT * FROM users WHERE upper($field) LIKE'%$find%'")

This code actually does the searching. We are choosing all the data from our table WHERE the the field they choose is LIKE their search string. We use upper () here to search the uppercase version of the fields. Earlier we converted our search term to uppercase as well. These two things together basically ignore case. Without this a search for "pizza" would not return a profile that had the word "Pizza" with a capitol P. We also use the '%' percentage on either side of our $find variable to indicate that we are not looking solely for that term but rather that term possibly contained in a body of text.

while($result = mysql_fetch_array( $data ))

This line and the lines below it start a loop that will cycle through and return all the data. We then choose what information to ECHO back to our user, and in what format.

$anymatches=mysql_num_rows($data);
if ($anymatches == 0)

This code counts the number of rows of results. If the number is 0, it means that no results were found. If this is the case, we let the user know that.

$anymatches=mysql_num_rows($data)

Finally, incase they forgot, we remind them of what they searched for.

Monday, February 8, 2010

Edit the row from the database

<?php

if(isset($_GET['user_id']))
{
$user_id=$_GET['user_id'];
}
else if(isset($_POST['user_id']))
{
$user_id=$_POST['user_id'];
}
else
{
$user_id=0;
}


if($user_id!=0)
{

//echo "$name $address $user_name $pass";
if (mysql_connect("localhost","root",""))
{

//echo "connected";
mysql_select_db("php_classes");



if(isset($_POST['button']))
{


$name=$_POST['name'];

$address=$_POST['address'];

$user_name=$_POST['user_name'];




$query1="select user_id from profile where user_id=$user_id";

$result1=mysql_query($query1);
if(mysql_num_rows($result1)==0)
{
echo "This username is not available";
}
else
{


$query="update profile set name='$name',address='$address',user_name='$user_name' where user_id=$user_id limit 1";
//echo $query;

$result=mysql_query($query);

if (mysql_affected_rows()==1)
{
echo "Data has been updated";
}
else
{
echo "Data has been not been updated";
}
}








}//end of submit



$query11="select * from profile where user_id=$user_id";
//echo $query11;
$result11=mysql_query($query11);
$rows=mysql_fetch_array($result11,MYSQL_ASSOC);



?>





<form id="form1" name="form1" method="post" action="edit.php">
<p>Name
<label>
<input type="text" name="name" id="name" value="<?php echo $rows['name']; ?>" />
</label>
</p>
<p>Address
<input type="text" name="address" id="address" value="<?php echo $rows['address']; ?>" />
</p>
<p>Username
<input type="text" name="user_name" id="user_name" value="<?php echo $rows['user_name']; ?>"/>
</p>
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>" />
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>


<?php
/*
mysql_connect()//connects
mysql_select_db()//
mysql_query()//passes query to mysql from php/
//CUD-Create-Unpdate-Delete---
//R-Read
mysql_affected_rows
mysql_num_rows
mysql_fetch_array
*/
}
else
{
echo "Could not connect to database";
}


}
else
{
echo "No user id Found";
}

?>
Edit the row from the database

list the users in the database

<?php


if (mysql_connect("localhost","root",""))
{

mysql_select_db("php_classes");

$query="select * from profile";
$result=mysql_query($query);

if (mysql_num_rows($result)>0)
{

?>
<table width="100%" border="1" cellspacing="0" cellpadding="0">

<tr>
<td>Name</td>
<td>Address</td>
<td>Username</td>
<td>Added</td>
<td>Delete</td>
<td>Edit</td>
</tr>

<?php
while ($rows=mysql_fetch_array($result,MYSQL_ASSOC))
{
?>
<tr>
<td><?php echo "{$rows['name']}"; ?></td>
<td><?php echo "{$rows['address']}"; ?></td>
<td><?php echo "{$rows['user_name']}"; ?></td>
<td><?php echo "{$rows['added_on']}"; ?></td>
<td><a href="delete_user.php?user_id=<?php echo "{$rows['user_id']}"; ?>">Delete</a></td>
<td><a href="edit.php?user_id=<?php echo "{$rows['user_id']}"; ?>">Edit</a></td>
</tr>

<?php

}//end of while
?>
</table>
<?php

}
else
{
echo "No Records found";
}



}
else
{
echo "Could not connect to database";
}



?>

list the users in the database

insert in the database using the php code

<?php

if(isset($_POST['button']))
{


$name=$_POST['name'];

$address=$_POST['address'];

$user_name=$_POST['user_name'];

$pass=$_POST['pass'];

//echo "$name $address $user_name $pass";
if (mysql_connect("localhost","root",""))
{

//echo "connected";
mysql_select_db("php_classes");

$query1="select user_id from profile where user_name=\"$user_name\"";

$result1=mysql_query($query1);
if(mysql_num_rows($result1)>0)
{
echo "This username is not available";
}
else
{


$query="insert into profile(name,address,user_name,pass,added_on) values ('$name','$address','$user_name',MD5('$pass'),NOW())";
//echo $query;

$result=mysql_query($query);

if (mysql_affected_rows()==1)
{
echo "You Are registered";
}
else
{
echo "You Are NOT registered";
}
}



}
else
{
echo "Could not connect to database";
}




}//end of submit






?>





<form id="form1" name="form1" method="post" action="register.php">
<p>Name
<label>
<input type="text" name="name" id="name" />
</label>
</p>
<p>Address
<input type="text" name="address" id="address" />
</p>
<p>Username
<input type="text" name="user_name" id="user_name" />
</p>
<p>Password
<input type="password" name="pass" id="pass" />
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>


<?php
/*
mysql_connect()//connects
mysql_select_db()//
mysql_query()//passes query to mysql from php/
//CUD-Create-Unpdate-Delete---
//R-Read
mysql_affected_rows
mysql_num_rows
mysql_fetch_array
*/


?>
insert in the database, insert in the mysql database, insert in the php and mysql database, insert in the database using the php code

delete user from the database

<?php
$user_id=$_GET['user_id'];

if(isset($_GET['submit']))
{

if (mysql_connect("localhost","root",""))
{
//echo "connected";
mysql_select_db("php_classes");

$confirm=$_GET['confirm'];

if ($confirm==1)
{


$query="delete from profile where user_id=$user_id limit 1";
//echo $query;

$result=mysql_query($query);

if (mysql_affected_rows()==1)
{
echo "User of ID $user_id has been deleted ";
}
else
{
echo "User of ID $user_id has NOT been deleted";
}

}
else
{
echo "The action was not done";
}


}
else
{
echo "Could not connect to database";
}



}




?>

<form method="get" action="delete_user.php">
Deleting user <?php echo $user_id; ?>
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>" /><br/>
<input type="radio" name="confirm" value="0" checked="checked"/>No   <input type="radio" name="confirm" value="1"/>Yes<br/>

<input type="submit" name="submit" value="Do Action"/>
</form>

delete user from the database, delete with the confirm from the database, delete and confirm in the same page

learn about tables rowspan and colspan

</head>

<body>

<table border="0" cellpadding="2" cellspacing="2" width="100%">


<tr>
<td width="33%">1</td>
<td colspan="2">

</td>
</tr>

<tr>

<td rowspan="2">2</td>
<td>1</td>
<td>1</td>
</tr>

<tr>
<td>1</td>
<td>2</td>

</tr>


</table>


</body>
</html>
learn about tables rowspan and colspan, example of rowspan, example of colspan, example of table in the html, example of table in php

Uses of stripslashes addslashes

<?php
echo "This is printed doc";
//printf("This is another print");
$user="Ram";
echo "This is $user<br/>";
echo 'This is $user<br/>';
$user='ram"s';
$user=addslashes($user);
echo "$user<br/>";
$user=stripslashes($user);
echo "$user<br/>";
//$query="select * from table where username =$user";
//echo $query;


$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str, ENT_QUOTES);


$test= htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $test;

echo md5("test");


echo nl2br("foo isn't\n bar");
$pass="ram1";
if($pass=="ram")
{
echo "Authorized";
}


echo "<br/>";

$text = '<p>Test paragraph.</p><!-- Comment --> <a href=\"#fragment\">Other text</a>';
echo strip_tags($text);

echo strlen("rupak");

echo "<br/>";

$text = '<p>Test paragraph.</p><!-- Comment --> <a href=\"#fragment\">Other text</a>';
echo str_replace("p","b",$text);

echo "<br/>";

$text1="Returns a string with backslashes in front of predefined charactersReturns a string with backslashes in front of predefined charactersReturns a string with backslashes in front of predefined charactersReturns a string with backslashes in front of predefined charactersReturns a string with backslashes in front of predefined charactersReturns a string with backslashes in front of predefined characters";
echo substr($text1,0,50);
echo "<br/>";
echo strtolower("TEXT");

echo "<br/>";
echo strtoupper("text");
echo "<br/>";

$result= strpos('abcde','g');
if($result!==FALSE)
{
echo "found";
}
else
{
echo "Not found";
}

echo "<br/>";

//
$email = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com



?>
Uses of stripslashes addslashes, example of stripslashes, example of addslashes, example of substr, example of strtoupper, example of strstr, example of strpos, example of strlen, example of str_replace, example of strip_tags, example of htmlspecials, example of md5

Sunday, February 7, 2010

use of explode function and file_get_contents functions

how can we hack the contents of others sites?
how can we links others site with ours?
how can we show others contents in our sites?
<?php
/*$data='<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>one</td>
</tr>
<tr>
<td>Two</td>
</tr>
<tr>
<td>Three</td>
</tr>
<tr>
<td>Four</td>
</tr>
<tr>
<td>Five</td>
</tr>
</table>';*/


$test=file_get_contents("http://www.cybernepal.com.np");

echo $test;



//$break=explode("</tr>",$data);
//print_r($break);

?>

knowledge about rowspan and colspan in our classes

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>

<body>

<table border="0" cellpadding="2" cellspacing="2" width="100%">


<tr>
<td width="33%">1</td>
<td colspan="2">

</td>
</tr>

<tr>

<td rowspan="2">2</td>
<td>1</td>
<td>1</td>
</tr>

<tr>
<td>1</td>
<td>2</td>

</tr>


</table>


</body>
</html>

Database structures for php classes

-- phpMyAdmin SQL Dump
-- version 3.1.3.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Feb 05, 2010 at 12:47 PM
-- Server version: 5.1.33
-- PHP Version: 5.2.9

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `php_classes`
--

-- --------------------------------------------------------

--
-- Table structure for table `profile`
--

CREATE TABLE IF NOT EXISTS `profile` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(254) NOT NULL,
`address` varchar(150) NOT NULL,
`user_name` varchar(50) NOT NULL,
`pass` varchar(40) NOT NULL,
`added_on` datetime NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

--
-- Dumping data for table `profile`
--

INSERT INTO `profile` (`user_id`, `name`, `address`, `user_name`, `pass`, `added_on`) VALUES
(1, 'Rupak', 'kathmandu', 'rupakr', 'd41d8cd98f00b204e9800998ecf8427e', '2010-02-05 17:24:09'),
(2, 'Jayaman', 'lalitpur', 'jaya', 'ce9689abdeab50b5bee3b56c7aadee27', '2010-02-05 17:27:09'),
(4, 'Sanjay', 'boudha', 'sanjay', '13ff58bd0f3da95d58fbe21d98436798', '2010-02-05 17:28:28'),
(5, 'Rupak', 'kathmandu', 'rupakr', 'd41d8cd98f00b204e9800998ecf8427e', '2010-02-05 18:26:14');

Wednesday, February 3, 2010

collection of mysql functions

mysql_affected_rows — Get number of affected rows in previous MySQL operation
mysql_client_encoding — Returns the name of the character set
mysql_close — Close MySQL connection
mysql_connect — Open a connection to a MySQL Server
mysql_create_db — Create a MySQL database
mysql_data_seek — Move internal result pointer
mysql_db_name — Get result data
mysql_db_query — Send a MySQL query
mysql_drop_db — Drop (delete) a MySQL database
mysql_errno — Returns the numerical value of the error message from previous MySQL operation
mysql_error — Returns the text of the error message from previous MySQL operation
mysql_escape_string — Escapes a string for use in a mysql_query
mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
mysql_fetch_assoc — Fetch a result row as an associative array
mysql_fetch_field — Get column information from a result and return as an object
mysql_fetch_lengths — Get the length of each output in a result
mysql_fetch_object — Fetch a result row as an object
mysql_fetch_row — Get a result row as an enumerated array
mysql_field_flags — Get the flags associated with the specified field in a result
mysql_field_len — Returns the length of the specified field
mysql_field_name — Get the name of the specified field in a result
mysql_field_seek — Set result pointer to a specified field offset
mysql_field_table — Get name of the table the specified field is in
mysql_field_type — Get the type of the specified field in a result
mysql_free_result — Free result memory
mysql_get_client_info — Get MySQL client info
mysql_get_host_info — Get MySQL host info
mysql_get_proto_info — Get MySQL protocol info
mysql_get_server_info — Get MySQL server info
mysql_info — Get information about the most recent query
mysql_insert_id — Get the ID generated in the last query
mysql_list_dbs — List databases available on a MySQL server
mysql_list_fields — List MySQL table fields
mysql_list_processes — List MySQL processes
mysql_list_tables — List tables in a MySQL database
mysql_num_fields — Get number of fields in result
mysql_num_rows — Get number of rows in result
mysql_pconnect — Open a persistent connection to a MySQL server
mysql_ping — Ping a server connection or reconnect if there is no connection
mysql_query — Send a MySQL query
mysql_real_escape_string — Escapes special characters in a string for use in a SQL statement
mysql_result — Get result data
mysql_select_db — Select a MySQL database
mysql_set_charset — Sets the client character set
mysql_stat — Get current system status
mysql_tablename — Get table name of field
mysql_thread_id — Return the current thread ID
mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the result rows.

Sending mail to many clients

<?php
include("connection.php");
if (!isset($_POST['submit'])):
?>

<html>
<head>
<title>Mailing List</title>
</head>

<body bgcolor="#D6DEE7">
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<table width="471" border="0">
<tr>
<td colspan="2"><b><h2 align="center">MAILING LIST ADMIN</h2></b></td>
</tr>
<tr>
<td width="143">Send message to:</td>
<td width="318"><select name="to" size="1" style="background-color: #F7F7F7">
<option selected value="all">Entire School
<OPTION value="primary">primary
<OPTION value="lower_secondary">lower secondary
<OPTION value="secondary">secondary
</select></td>
</tr>
<tr>
<td>Title or Subject: </td>
<td><input name="subject" type=text maxlength=100 size=40></td>
</tr>
<tr>
<td valign="top">Message:</td>
<td><textarea wrap name="message" rows=10 cols=45></textarea></td>
</tr>
<tr>
<td colspan="2"><div align="center">
<input type=submit name="submit" value="SUBMIT">
</div></td>

</tr>
</table>

</form>
</body>
</html>

<?php else:

$to = $_POST['to'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$country = $_POST['country'];

if ("all" == $to) {
$x = 1;
$hold = 50; // quantity of emails sent before 3 sec delay
$emails = mysql_query("SELECT email FROM schooldetails");
while ($sendemail = mysql_fetch_array($emails)) {
$email = $sendemail["email"];
mail($email, $subject,
$message, "From:Your name <you@whatever.com>");

$x++;
if($x == $hold) { // When $x is equal to $hold, a 3 sec delay will occur avoiding php to timeout
sleep(3);
$x = 0;
}
} // end of while loop
echo "send to all";
}
elseif ("primary" == $to) {
$x = 1;
$hold = 50; // quantity of emails sent before 3 sec delay
$emails = mysql_query("SELECT email FROM schooldetails where type_id='1'");
while ($sendemail = mysql_fetch_array($emails)) {
$email = $sendemail["email"];
mail($email, $subject,
$message, "From:Your name <you@whatever.com>");

$x++;
if($x == $hold) { // When $x is equal to $hold, a 3 sec delay will occur avoiding php to timeout
sleep(3);
$x = 0;
}
} // end of while loop
echo "send to primary";
}
elseif ("lowersecondary" == $to) {
$x = 1;
$hold = 50; // quantity of emails sent before 3 sec delay
$emails = mysql_query("SELECT email FROM schooldetails where type_id='2'");
while ($sendemail = mysql_fetch_array($emails)) {
$email = $sendemail["email"];
mail($email, $subject,
$message, "From:Your name <you@whatever.com>");

$x++;
if($x == $hold) { // When $x is equal to $hold, a 3 sec delay will occur avoiding php to timeout
sleep(3);
$x = 0;
}
} // end of while loop
echo "send to lower secondary";
}
elseif ("secondary" == $to) {
$x = 1;
$hold = 50; // quantity of emails sent before 3 sec delay
$emails = mysql_query("SELECT email FROM schooldetails where type_id='3'");
while ($sendemail = mysql_fetch_array($emails)) {
$email = $sendemail["email"];
mail($email, $subject, $message, "From:Your name <you@whatever.com>");

$x++;
if($x == $hold) { // When $x is equal to $hold, a 3 sec delay will occur avoiding php to timeout
sleep(3);
$x = 0;
}
} // end of while loop
echo "send to secondary";
}
?>
<html>
<head>
</head>
<body>
SUCCESS!
</body>
</html>
<?php endif; ?>
Sending mail to many clients, sending mail to according to group

form validation using javascript

<html>
<head>
<title>Untitled Page</title>

<script type="text/javascript">
<!--

function BatchValidation()
{
var validationMessage="";
if(document.form1.txtFName.value=="")
{
validationMessage+="\n First Name is the required field!";
}
if(document.form1.txtLName.value=="")
{
validationMessage+="\n Last Name is the required field!";
}
if(!IsCorrectEmailFormat(document.form1.txtEmail.value))
{
validationMessage+="\n Email address is not valid format!";
}

if(isNaN(document.form1.txtPhoneNo.value))
{
validationMessage+="\n Phone number is number!";
}
if(isNaN(document.form1.txtMobileNo.value))
{
validationMessage+="\n Mobile number is number!";
}
if(validationMessage.length>0)
{
alert(validationMessage);
return false;
}
else
{
return true;
}
}

function IsCorrectEmailFormat(strEmail)
{
var at="@"
var dot="."
var atPos=strEmail.indexOf(at)
var lstr=strEmail.length
var dotPos=strEmail.indexOf(dot)

if (atPos==-1 || atPos==0 || atPos==lstr){
return false
}
if (dotPos==-1 || dotPos==0 || dotPos==lstr){
return false
}

if (strEmail.indexOf(at,(atPos+1))!=-1){
return false
}
if (strEmail.substring(atPos+1,atPos+2)==dot){
return false
}

if (strEmail.indexOf(dot,(atPos+2))==-1){
return false
}

if (strEmail.indexOf(" ")!=-1){
return false
}
if(dotPos<atPos)
{
return false;
}
return true
}

function CheckRequiredField(strFieldName,tag)
{
if(tag.value=="")
{
ErrorMessage.innerHTML=strFieldName + " is Required field!";
}
}

function RealTimeEmailValidation(strEmail)
{
if(strEmail.toString().length>0)
{
if(!IsCorrectEmailFormat(strEmail))
{
ErrorMessage.innerHTML="Email is not in correct format!";
}
}
}

function RealTimeNumberValidation(num)
{
if(isNaN(num))
{
ErrorMessage.innerHTML="Phone no is number!";
}
}

function NumberOnly(aTexField,e)
{
var keyCode = window.event? window.event.keyCode : e.which;
if(keyCode>47 && keyCode<58)
{
}
else
{
window.setTimeout("RemoveLastChar('"+aTexField.id+"')",100);
}
}
function RemoveLastChar(aTextFieldID)
{
var aTextField=document.getElementById(aTextFieldID);
var val=aTextField.value.toString();
var len=val.length;
val=val.substring(0,len-1);
aTextField.value=val;
}

function IsEmpty(aTextField) {
if ((aTextField.value.length==0) ||
(aTextField.value==null)) {
return true;
}
else
{
return false;
}
}

function IsValidEmail(aTextField)
{
var emailRegxp = /^[a-zA-Z\.][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/
if(emailRegxp.test(aTextField.value)!=true)
{
return false;
}
else
{
return true;
}

}
// -->
</script>

</head>
<body>
<form id="form1" name="form1" onsubmit="return BatchValidation();">
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="txtFName" id="txtFName" onblur="CheckRequiredField('First Name',this);" />
</td>
</tr>
<tr>
<td>
Last Name:
</td>
<td>
<input type="text" name="txtLName" id="txtLName" onblur="CheckRequiredField('Last Name',this);" />
</td>
</tr>
<tr>
<td>
Address:
</td>
<td>
<input type="text" name="txtAddress" id="txtAddress" />
</td>
</tr>
<tr>
<td>
Email:
</td>
<td>
<input type="text" name="txtEmail" id="txtEmail" onblur="RealTimeEmailValidation(this.value);" />
</td>
</tr>
<tr>
<td>
Phone No:
</td>
<td>
<input type="text" name="txtPhoneNo" id="txtPhoneNo" onblur="RealTimeNumberValidation(this.value)"/>
</td>
</tr>
<tr>
<td>
Mobile No:
</td>
<td>
<input type="text" name="txtMobileNo" id="txtMobileNo" onkeydown="NumberOnly(this,event)" />
</td>
</tr>
<tr>
<td colspan="2"><span id="ErrorMessage" style="color:Red;"></span></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save" /> <input type="reset" value="Cancel" />
</td>
</tr>
</table>
</form>
</body>
</html>

create some sophisticated web sites

<?
$message = "";
$emailclass = "basictext";
$username = "";

if ($_POST['process'] == 1) {

$pattern = '/.*@.*\..*/';
$email = $_POST['email'];
$urlname = urlencode($$_POST['username']);

if (preg_match($pattern, $_POST['email']) > 0) {
// Here's where you would store
// the data in a database...
header(
"location: thankyou.php?&username=$urlname");
}
$message = "Please enter a valid email address.";
$username = $_POST['name'];
$emailclass = "errortext";
}
?>

<html>
<style>
.basictext {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px; color:#000066;
}
.errortext {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px; color:#C00000; font-weight: bold;
}
</style>
<body>
<form action="email.php" method="post">
<? if ($message != "") {
print '<span class="errortext">'.
$message."<span><br>\n";
}
?>
<span class="<?print $emailclass; ?>">
Email address:</span>
<input name="email" type="text"
class="<? print $emailclass; ?>"><br>

<span class="basictext">Your name:</span>
<input name="name" type="text" class="basictext"
value="<?print $username; ?>"><br>
<input type="hidden" name="process" value="1">
<input type="submit" name="Button1" value="Sign up!">
</form>
</body></html>
How it Works
The first section is the processing section. Notice the trick: if the $_POST array contains a key called Process with a value of 1, then begin processing; otherwise, just continue on. In other words, the first time the user opens the page, processing will not take place. You can see farther down that the form includes a hidden field called process with the value 1. Thus, when the user clicks the submit button, the page will load again, but this time processing will take place. Voila! The problem of the chicken and egg has been solved!
(Note, however, that the purists might balk at the fact that I'm playing on a feature in PHP: ff the $_POST['process'] variable doesn't exist, as is the case the first time the page loads, PHP still lets me test it against the value of 1; I'll simply get back a false. If this bothers you, you can add an isset call to first check whether $_POST['process'] even exists.)
The processing here is simple. I threw together a simple regular expression to check for an email address. (However, please don't use this regular expression in your own production code, as it's not foolproof; for a better one, check out the PHP Cookbook.) If the email address matches the regular expression, then all is fine and I issue a redirect to the next page, called thankyou.php. If the address doesn't survive the regular expression test, then I stay on the page and store a value in the $message variable.
Next, notice how I play with the styles: I have two styles defined inside of the <head> tag. One is for the basic text, a basic dark blue. The other is for bold red text used with errors to attract attention to the problem. In the PHP code, I store the basic text-style name inside of the $emailclass variable. If the code encounters an invalid email address, it changes the value of $emailclass to errortext. Then, when I create the label for the email address and the text box for the email address, I use the class stored in $emailclass, like so:
class="<?print $emailclass; ?>">
Thus, when all is fine, the HTML displays regular text. When there's a problem, it displays bold red text.
Notice also that I store some defaults in the fields. Initially, $username holds an empty string. On the return trip through the file, if the validation fails, I put the $_POST['name'] value back into the $username variable. (Remember, and this is important: on the return trip through the file, you are running the program as if it's brand new. Any variables you set the previous time are no longer present, unless you use a session variable; see Session handling functions for more information.) Later down in the code, I stuff the $username value into the form, like so:
<input name="name" type="text" class="basictext" value="<?print $username; ?>"><br>
Thus, if the user enters an improper email address, when the form returns, it will have the username already filled in. This technique is extremely important for user-friendly forms, because if the user forgets an @ sign in the email address (or the AOL users just type a screen name without @aol.com), he or she doesn't want to have to retype everything else into the form. This way, the form will return already populated with everything the user already typed in. In this case, I also decided to fill in the email address box with what the user previously typed, just so he or she can see the incorrect value and fix it.
The final thing to show you about this code is how I pass the value of the username on to the next page. Notice first that the form uses a POST method. Whenever you're sending out passwords, you want to use a POST method, since a GET method will show the password in the URL (and in the history file). People wouldn't be too happy about that if somebody is glancing over their shoulders. Of course, I'm not using a password in this example, but you might be in your own project; thus, I used the POST method as a demonstration.
However, the next page (in this case, thankyou.php) might well need access to the data that the user entered. The easiest way to pass it is through a GET, like so:
header("location: thankyou.php?&username=$urlname");
(I called urlencode so that the spaces and any other unusual characters will make it across.) Yes, I'm using a GET method, even though I just raved about the importance of using a POST method. However, I didn't pass the email address. The reason is that you would probably go ahead and store or process the username and password right inside of the processing code before calling header, rather than waiting until you get to the next page, in this case thankyou.php. Why now? Because you're already doing all the verifying; you might as well do the real processing, as well. For example, in a signup form, you might need to test whether the chosen username already exists; if it does, then you'll issue a message to the user that the username exists and to try a different one. If all is fine, you could go ahead and store the information in the database, before proceeding to the thankyou.php page. (It's possible, then, that you won't have to pass anything at all to the thankyou.php page, and therefore won't even need the ?&username= portion of the URL in the header call.)
More Possibilities
Here are some things that you could do with this technique:
• Have the user enter an email address twice. In the processing, check if the two match, and if not, print a message stating that they don't match.
• When a user signs up for a new account, test the chosen username and password against the database. If the username already exists, start a loop where you add on some random numbers to the username until you locate one that doesn't already exist in the database, and then suggest this username to the user.
• Check if the user left any required fields blank. Add a message along the lines of, "Please fill in the missing fields," and note the missing fields with red labels, being sure to fill in the other fields with whatever the user previously typed in.
• Make sure the password's length is within the required size. If it's less than eight characters, for example, put a message stating that the password must be at least eight characters.
You can even get fancier. When a user logs out, you could send the user back to a login.php page, with an added message saying, "You have been logged out. Use this form if you wish to log back in." How would you do that? After logging the user out, redirect the user back to the login.php page, passing a unique value (such as 2) in with the URL, as in login.php?process=2. Then add an if block to the login.php page checking the $_GET['process'] for the value 2. If the comparison succeeds, set the message appropriately. That way, you don't need a separate login page just for the extra message. (You are free to mix $_GET and $_POST all within the same page. PHP handles it just fine.)
Conclusion
Using this technique, you can easily create some sophisticated web sites that don't require a lot of duplicate code and unnecessary processing, all while sticking to our beloved PHP without having to touch either JavaScript or ASP.

Simple retrieve, amend and update MySQL database

PHP Scripts
Simple retrieve, amend and update MySQL database
1. 1st page to aquire reference ( display all to make it easy)
2. 2nd page display results and allow viewer to change
3. Update the database
amend.php
<html><TD WIDTH="29%" HEIGHT="60"><DIV ALIGN="LEFT"><BR>Input
the Reference, to make sure we have the right one:<BR><BR><FONT SIZE="1">(quick
reference listed below for your convenience)</FONT></DIV>
<form method=POST action="amend1.php">
<DIV ALIGN="LEFT"><INPUT TYPE="text" NAME="record" SIZE="50" MAXLENGTH="50"><BR><BR><IMG SRC="search.jpg" WIDTH="51" HEIGHT="46" ALIGN="ABSMIDDLE" BORDER="1"><INPUT TYPE="submit" NAME="go" VALUE="Search on that Input"></DIV></form></TD></TR><TR><TD WIDTH="29%"><DIV ALIGN="LEFT">
<?php
// Show simple format of the records so person can choose the reference name/number
// this is then passed to the next page, for all details

$db = mysql_connect("db_host", "db_name", "db_password");
mysql_select_db("database",$db) or die ('Unable to connect to database');
$q="SELECT * FROM table ORDER BY reference ASC";
$result = mysql_query( $q, $db )
or die(" - Failed More Information:<br><pre>$q</pre><br>Error: " . mysql_error());
$num_rows = mysql_num_rows($result);
if ($myrow = mysql_fetch_array($result)) {
echo "<br>A Quick View<BR><br>";
echo "<table border=1>\n";
echo "<tr><td><b>Ref:</b></td><td>Description:</td><td>Consultant:</td><td>Thumb:</td></tr>\n";
do {
printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n", $myrow["reference"], $myrow["shortdescription"], $myrow["consultant"], $myrow["thumb"]);
} while ($myrow = mysql_fetch_array($result));
echo "</table>\n";
} else {
echo "$ref: That record appears to be unavailable";
}
mysql_free_result($result);
mysql_close($db);
?></DIV></TD></html>
________________________________________
amend1.php
<?PHP
session_start();
?>
<HTML>
<?php
$record = $_POST['record'];
echo "Reference: $record<br><BR>";
$host = "db_host";
$login_name = "db_name";
$password = "db_password";
//Connecting to MYSQL
MySQL_connect("$host","$login_name","$password");
//Select the database we want to use
mysql_select_db("database") or die("Could not find database");
$result=mysql_query(" SELECT * FROM table WHERE reference='$record'");
$num=mysql_num_rows($result);
$i=0;
while ($i < $num) {
// collect all details for our one reference
$description=mysql_result($result,$i,"description");
$text2=mysql_result($result,$i,"text2");
$reference=mysql_result($result,$i,"reference");
$thumb=mysql_result($result,$i,"thumb");
$img1=mysql_result($result,$i,"image1");
$img2=mysql_result($result,$i,"image2");
$img3=mysql_result($result,$i,"image3");

$f='<font face=Verdana,Arial,Helvetica size=2 Color=Blue';
$view='<img src=http://your_website/thumbs/';
echo "<br>$view$thumb.jpg><br><br>";
//next we display only the details we want to allow to be changed in a form object
// the other details that we won't allow to be changed can be echoed to the screen
//note the hidden input line 3 below. We don't need to echo it to the screen
?>
<TABLE WIDTH="100%" CELLPADDING="10" CELLSPACING="0" BORDER="2"> <TR ALIGN="center" VALIGN="top">
<TD ALIGN="center" COLSPAN="1" ROWSPAN="1" BGCOLOR="#F2F2F2">
<FORM ACTION="amend2.php" METHOD="post">
<P ALIGN="LEFT">
<INPUT TYPE="hidden" NAME="ud_id" VALUE="<? echo "$record" ?>">
<BR>Description1:<BR><TEXTAREA NAME="ud_description" COLS="50" ROWS="4">
<? echo "$description"?></TEXTAREA></P><P ALIGN="LEFT">Description:<BR>
<TEXTAREA NAME="ud_text2" COLS="50" ROWS="4"><? echo "$text2"?></TEXTAREA></P><HR><B>
</B><P ALIGN="LEFT">Thumbnail:<BR> <INPUT TYPE="text" NAME="ud_thumb" VALUE="<? echo "$thumb"?>" SIZE="30" MAXLENGTH="50"></P><P ALIGN="LEFT">Image
1 :<BR> <INPUT TYPE="text" NAME="ud_img1" VALUE="<? echo "$img1"?>" SIZE="30" MAXLENGTH="50"></P><P ALIGN="LEFT">Image
2 :<BR> <INPUT TYPE="text" NAME="ud_img2" VALUE="<? echo "$img2"?>" SIZE="30" MAXLENGTH="50"></P><P ALIGN="LEFT">Image
3 :<BR> <INPUT TYPE="text" NAME="ud_img3" VALUE="<? echo "$img3"?>" SIZE="30" MAXLENGTH="50"><BR><BR>
</P><P><INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"> </P></FORM></TD></TR></TABLE>
<?
++$i;
}
?>
________________________________________
amend2.php
<?PHP
session_start();
?>
<?php
$ud_id=$_POST['ud_id'];
$ud_description=$_POST['ud_description'];
$ud_text2=$_POST['ud_text2'];
$ud_thumb=$_POST['ud_thumb'];
$ud_img1=$_POST['ud_img1'];
$ud_img2=$_POST['ud_img2'];
$ud_img3=$_POST['ud_img3'];
if ($ud_id == "") echo "! No identifier retrieved";
else
echo "Amending record $ud_id";
//clean up any carriage returns etc
$ud_description = preg_replace("/[\n\r]*/","",$ud_description);
$ud_text2 = preg_replace("/[\n\r]*/","",$ud_text2);
$host = "db_host";
$login_name = "db_name";
$password = "db_password";
//Connecting to MYSQL
MySQL_connect("$host","$login_name","$password");
//Select the database we want to use
mysql_select_db("db_database") or die("Could not select database");
mysql_query(" UPDATE db_table
SET description='$ud_description', text2='$ud_text2', thumb='$ud_thumb', image1='$ud_img1', image2='$ud_img2', image3='$ud_img3', WHERE reference='$ud_id'");
echo "<BR>Record $ud_id <-- Updated<BR><BR>";
?>
<?php
//if you want to check it's ok, display new data
echo "Search on $ud_id<BR>";
$db = mysql_connect("host", "name", "password");
mysql_select_db("db_database",$db) or die ('Unable to connect to database');
$q="SELECT * FROM db_table WHERE reference ='$ud_id'";
$result = mysql_query( $q, $db )
or die(" - Failed More Information:<br><pre>$q</pre><br>Error: " . mysql_error());
$num_rows = mysql_num_rows($result);
if ($myrow = mysql_fetch_array($result)) {
$thumb='<img src=http://your_website/thumbs/';

//if the record leads to a specific page
$web='http://www.your_website/detail/index.php?name=';
echo "<table border=0>\n";
echo "<tr><td></td><td></td><td></td><td></td></tr>\n";

do {
printf("<tr><td>$thumb%s.jpg></td><td>%s</td><td>%s</td><td>%s</td>
</tr>\n", $myrow["thumb"], $myrow["reference"], $myrow["description"], $myrow["text2"]);
} while ($myrow = mysql_fetch_array($result));
echo "</table>\n";
} else {
echo "Sorry, no records were found";
}
mysql_free_result($result);
mysql_close($db);
session_destroy();
?>

show time with javascripts code

<html>
<head>
<script type="text/javascript">
function JSclock()
{

var time=new Date();
var hour=time.getHours();

var min=time.getMinutes();
var second=time.getSeconds();
var temp=""+((hour>12) ? eval(hour-12) : hour);
temp+=((min<10) ? ":0" : " : ") + min;
temp+=((second<10) ? ":0" : " :")+second;
temp+=((hour>=12) ? "pm" : "am");
document.getElementById("currentTime").innerHTML=temp;
setTimeout("JSclock()",1000);
}
</script>
</head>
<body onload="JSclock()">
<span id="currentTime"></span>
</body>
</html>

show time with javascripts code, javascript code, time giving javascript code

Calender Code "Javascript code that must be at js/src" named unittest.js

// script.aculo.us unittest.js v1.6.5, Wed Nov 08 14:17:49 CET 2006

// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005, 2006 Jon Tirsen (http://www.tirsen.com)
// (c) 2005, 2006 Michael Schuerig (http://www.schuerig.de/michael/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

// experimental, Firefox-only
Event.simulateMouse = function(element, eventName) {
var options = Object.extend({
pointerX: 0,
pointerY: 0,
buttons: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false
}, arguments[2] || {});
var oEvent = document.createEvent("MouseEvents");
oEvent.initMouseEvent(eventName, true, true, document.defaultView,
options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element));

if(this.mark) Element.remove(this.mark);
this.mark = document.createElement('div');
this.mark.appendChild(document.createTextNode(" "));
document.body.appendChild(this.mark);
this.mark.style.position = 'absolute';
this.mark.style.top = options.pointerY + "px";
this.mark.style.left = options.pointerX + "px";
this.mark.style.width = "5px";
this.mark.style.height = "5px;";
this.mark.style.borderTop = "1px solid red;"
this.mark.style.borderLeft = "1px solid red;"

if(this.step)
alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));

$(element).dispatchEvent(oEvent);
};

// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
// You need to downgrade to 1.0.4 for now to get this working
// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
Event.simulateKey = function(element, eventName) {
var options = Object.extend({
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: 0,
charCode: 0
}, arguments[2] || {});

var oEvent = document.createEvent("KeyEvents");
oEvent.initKeyEvent(eventName, true, true, window,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.keyCode, options.charCode );
$(element).dispatchEvent(oEvent);
};

Event.simulateKeys = function(element, command) {
for(var i=0; i<command.length; i++) {
Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
}
};

var Test = {}
Test.Unit = {};

// security exception workaround
Test.Unit.inspect = Object.inspect;

Test.Unit.Logger = Class.create();
Test.Unit.Logger.prototype = {
initialize: function(log) {
this.log = $(log);
if (this.log) {
this._createLogTable();
}
},
start: function(testName) {
if (!this.log) return;
this.testName = testName;
this.lastLogLine = document.createElement('tr');
this.statusCell = document.createElement('td');
this.nameCell = document.createElement('td');
this.nameCell.className = "nameCell";
this.nameCell.appendChild(document.createTextNode(testName));
this.messageCell = document.createElement('td');
this.lastLogLine.appendChild(this.statusCell);
this.lastLogLine.appendChild(this.nameCell);
this.lastLogLine.appendChild(this.messageCell);
this.loglines.appendChild(this.lastLogLine);
},
finish: function(status, summary) {
if (!this.log) return;
this.lastLogLine.className = status;
this.statusCell.innerHTML = status;
this.messageCell.innerHTML = this._toHTML(summary);
this.addLinksToResults();
},
message: function(message) {
if (!this.log) return;
this.messageCell.innerHTML = this._toHTML(message);
},
summary: function(summary) {
if (!this.log) return;
this.logsummary.innerHTML = this._toHTML(summary);
},
_createLogTable: function() {
this.log.innerHTML =
'<div id="logsummary"></div>' +
'<table id="logtable">' +
'<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
'<tbody id="loglines"></tbody>' +
'</table>';
this.logsummary = $('logsummary')
this.loglines = $('loglines');
},
_toHTML: function(txt) {
return txt.escapeHTML().replace(/\n/g,"<br/>");
},
addLinksToResults: function(){
$$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run only this test"
Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
});
$$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run all tests"
Event.observe(td, 'click', function(){ window.location.search = "";});
});
}
}

Test.Unit.Runner = Class.create();
Test.Unit.Runner.prototype = {
initialize: function(testcases) {
this.options = Object.extend({
testLog: 'testlog'
}, arguments[1] || {});
this.options.resultsURL = this.parseResultsURLQueryParameter();
this.options.tests = this.parseTestsQueryParameter();
if (this.options.testLog) {
this.options.testLog = $(this.options.testLog) || null;
}
if(this.options.tests) {
this.tests = [];
for(var i = 0; i < this.options.tests.length; i++) {
if(/^test/.test(this.options.tests[i])) {
this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
}
}
} else {
if (this.options.test) {
this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
} else {
this.tests = [];
for(var testcase in testcases) {
if(/^test/.test(testcase)) {
this.tests.push(
new Test.Unit.Testcase(
this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
testcases[testcase], testcases["setup"], testcases["teardown"]
));
}
}
}
}
this.currentTest = 0;
this.logger = new Test.Unit.Logger(this.options.testLog);
setTimeout(this.runTests.bind(this), 1000);
},
parseResultsURLQueryParameter: function() {
return window.location.search.parseQuery()["resultsURL"];
},
parseTestsQueryParameter: function(){
if (window.location.search.parseQuery()["tests"]){
return window.location.search.parseQuery()["tests"].split(',');
};
},
// Returns:
// "ERROR" if there was an error,
// "FAILURE" if there was a failure, or
// "SUCCESS" if there was neither
getResult: function() {
var hasFailure = false;
for(var i=0;i<this.tests.length;i++) {
if (this.tests[i].errors > 0) {
return "ERROR";
}
if (this.tests[i].failures > 0) {
hasFailure = true;
}
}
if (hasFailure) {
return "FAILURE";
} else {
return "SUCCESS";
}
},
postResults: function() {
if (this.options.resultsURL) {
new Ajax.Request(this.options.resultsURL,
{ method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
}
},
runTests: function() {
var test = this.tests[this.currentTest];
if (!test) {
// finished!
this.postResults();
this.logger.summary(this.summary());
return;
}
if(!test.isWaiting) {
this.logger.start(test.name);
}
test.run();
if(test.isWaiting) {
this.logger.message("Waiting for " + test.timeToWait + "ms");
setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
} else {
this.logger.finish(test.status(), test.summary());
this.currentTest++;
// tail recursive, hopefully the browser will skip the stackframe
this.runTests();
}
},
summary: function() {
var assertions = 0;
var failures = 0;
var errors = 0;
var messages = [];
for(var i=0;i<this.tests.length;i++) {
assertions += this.tests[i].assertions;
failures += this.tests[i].failures;
errors += this.tests[i].errors;
}
return (
(this.options.context ? this.options.context + ': ': '') +
this.tests.length + " tests, " +
assertions + " assertions, " +
failures + " failures, " +
errors + " errors");
}
}

Test.Unit.Assertions = Class.create();
Test.Unit.Assertions.prototype = {
initialize: function() {
this.assertions = 0;
this.failures = 0;
this.errors = 0;
this.messages = [];
},
summary: function() {
return (
this.assertions + " assertions, " +
this.failures + " failures, " +
this.errors + " errors" + "\n" +
this.messages.join("\n"));
},
pass: function() {
this.assertions++;
},
fail: function(message) {
this.failures++;
this.messages.push("Failure: " + message);
},
info: function(message) {
this.messages.push("Info: " + message);
},
error: function(error) {
this.errors++;
this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
},
status: function() {
if (this.failures > 0) return 'failed';
if (this.errors > 0) return 'error';
return 'passed';
},
assert: function(expression) {
var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
try { expression ? this.pass() :
this.fail(message); }
catch(e) { this.error(e); }
},
assertEqual: function(expected, actual) {
var message = arguments[2] || "assertEqual";
try { (expected == actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertEnumEqual: function(expected, actual) {
var message = arguments[2] || "assertEnumEqual";
try { $A(expected).length == $A(actual).length &&
expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
', actual ' + Test.Unit.inspect(actual)); }
catch(e) { this.error(e); }
},
assertNotEqual: function(expected, actual) {
var message = arguments[2] || "assertNotEqual";
try { (expected != actual) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertIdentical: function(expected, actual) {
var message = arguments[2] || "assertIdentical";
try { (expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNotIdentical: function(expected, actual) {
var message = arguments[2] || "assertNotIdentical";
try { !(expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNull: function(obj) {
var message = arguments[1] || 'assertNull'
try { (obj==null) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
catch(e) { this.error(e); }
},
assertMatch: function(expected, actual) {
var message = arguments[2] || 'assertMatch';
var regex = new RegExp(expected);
try { (regex.exec(actual)) ? this.pass() :
this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertHidden: function(element) {
var message = arguments[1] || 'assertHidden';
this.assertEqual("none", element.style.display, message);
},
assertNotNull: function(object) {
var message = arguments[1] || 'assertNotNull';
this.assert(object != null, message);
},
assertType: function(expected, actual) {
var message = arguments[2] || 'assertType';
try {
(actual.constructor == expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertNotOfType: function(expected, actual) {
var message = arguments[2] || 'assertNotOfType';
try {
(actual.constructor != expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertInstanceOf';
try {
(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was not an instance of the expected type"); }
catch(e) { this.error(e); }
},
assertNotInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertNotInstanceOf';
try {
!(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was an instance of the not expected type"); }
catch(e) { this.error(e); }
},
assertRespondsTo: function(method, obj) {
var message = arguments[2] || 'assertRespondsTo';
try {
(obj[method] && typeof obj[method] == 'function') ? this.pass() :
this.fail(message + ": object doesn't respond to [" + method + "]"); }
catch(e) { this.error(e); }
},
assertReturnsTrue: function(method, obj) {
var message = arguments[2] || 'assertReturnsTrue';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
m() ? this.pass() :
this.fail(message + ": method returned false"); }
catch(e) { this.error(e); }
},
assertReturnsFalse: function(method, obj) {
var message = arguments[2] || 'assertReturnsFalse';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
!m() ? this.pass() :
this.fail(message + ": method returned true"); }
catch(e) { this.error(e); }
},
assertRaise: function(exceptionName, method) {
var message = arguments[2] || 'assertRaise';
try {
method();
this.fail(message + ": exception expected but none was raised"); }
catch(e) {
(e.name==exceptionName) ? this.pass() : this.error(e);
}
},
assertElementsMatch: function() {
var expressions = $A(arguments), elements = $A(expressions.shift());
if (elements.length != expressions.length) {
this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
return false;
}
elements.zip(expressions).all(function(pair, index) {
var element = $(pair.first()), expression = pair.last();
if (element.match(expression)) return true;
this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
}.bind(this)) && this.pass();
},
assertElementMatches: function(element, expression) {
this.assertElementsMatch([element], expression);
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
},
_isVisible: function(element) {
element = $(element);
if(!element.parentNode) return true;
this.assertNotNull(element);
if(element.style && Element.getStyle(element, 'display') == 'none')
return false;

return this._isVisible(element.parentNode);
},
assertNotVisible: function(element) {
this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
},
assertVisible: function(element) {
this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
}
}

Test.Unit.Testcase = Class.create();
Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
initialize: function(name, test, setup, teardown) {
Test.Unit.Assertions.prototype.initialize.bind(this)();
this.name = name;

if(typeof test == 'string') {
test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
this.test = function() {
eval('with(this){'+test+'}');
}
} else {
this.test = test || function() {};
}

this.setup = setup || function() {};
this.teardown = teardown || function() {};
this.isWaiting = false;
this.timeToWait = 1000;
},
wait: function(time, nextPart) {
this.isWaiting = true;
this.test = nextPart;
this.timeToWait = time;
},
run: function() {
try {
try {
if (!this.isWaiting) this.setup.bind(this)();
this.isWaiting = false;
this.test.bind(this)();
} finally {
if(!this.isWaiting) {
this.teardown.bind(this)();
}
}
}
catch(e) { this.error(e); }
}
});

// *EXPERIMENTAL* BDD-style testing to please non-technical folk
// This draws many ideas from RSpec http://rspec.rubyforge.org/

Test.setupBDDExtensionMethods = function(){
var METHODMAP = {
shouldEqual: 'assertEqual',
shouldNotEqual: 'assertNotEqual',
shouldEqualEnum: 'assertEnumEqual',
shouldBeA: 'assertType',
shouldNotBeA: 'assertNotOfType',
shouldBeAn: 'assertType',
shouldNotBeAn: 'assertNotOfType',
shouldBeNull: 'assertNull',
shouldNotBeNull: 'assertNotNull',

shouldBe: 'assertReturnsTrue',
shouldNotBe: 'assertReturnsFalse',
shouldRespondTo: 'assertRespondsTo'
};
Test.BDDMethods = {};
for(m in METHODMAP) {
Test.BDDMethods[m] = eval(
'function(){'+
'var args = $A(arguments);'+
'var scope = args.shift();'+
'scope.'+METHODMAP[m]+'.apply(scope,(args || []).concat([this])); }');
}
[Array.prototype, String.prototype, Number.prototype].each(
function(p){ Object.extend(p, Test.BDDMethods) }
);
}

Test.context = function(name, spec, log){
Test.setupBDDExtensionMethods();

var compiledSpec = {};
var titles = {};
for(specName in spec) {
switch(specName){
case "setup":
case "teardown":
compiledSpec[specName] = spec[specName];
break;
default:
var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
var body = spec[specName].toString().split('\n').slice(1);
if(/^\{/.test(body[0])) body = body.slice(1);
body.pop();
body = body.map(function(statement){
return statement.strip()
});
compiledSpec[testName] = body.join('\n');
titles[testName] = specName;
}
}
new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
};