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);
?>
Sunday, February 7, 2010
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>
<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');
-- 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.
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
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>
<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.
$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();
?>
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
<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 });
};
// 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 });
};
Subscribe to:
Posts (Atom)
-
Why do niggers wear wide brimmed hats? So birds won't shit on their lips. How do you stop black kids from jumping on your bed? Put Velcr...
-
php, tutorial, sql, video, css, user, login, cookies, lifeg0eson666, marcus, recck, youtube, online, science, A PHP Tutorial creating a User...
-
Building a CMS with PHP and MYSQL Pat 2 video, php tutorials video, php and mysql to make cms video