I created a program where u type in the date and time and then on clicking submit, it tells you whether the typed in date and time are same as the current date and time.. the problem i am having with the time part is that no matter what time i put in, it says "same time" idk why. The date one is working fine but the time one isn't.
<?php
session_start();
$EntryError=$EntryTimeError="";
if (isset($_POST['submit'])){
$entrydate = $EntryTime = "";
$errorOccured = false;
if (isset($_POST['tsmdate'])){
$entrydate = trim($_POST['tsmdate']);
if (strlen($entrydate) == 0){
$EntryError = "date is missing";
$errorOccured = true;
}
else{
$presentDate=date('Y-m-d');
if(strtotime($entrydate) == strtotime($presentDate))
{
echo "same date";
}
else{
echo "different date";
}
}
}
else{
$EntryError = "date is missing";
}
if (isset($_POST['tsmTime'])){
$EntryTime = trim($_POST['tsmTime']);
if (strlen($EntryTime) == 0){
$EntryTimeError = "time is missing";
$errorOccured = true;
}
else{
$EntryTimeError = "time is missing";
$presentTime= date('h:i A', strtotime($EntryTime));
if(strtotime($EntryTime) == strtotime($presentTime))
{
echo "same time";
}
else{
echo "different time";
}
}
}
else{
$EntrytError = "time is missing";
}
}
?>
<html>
<head>
</head>
<body>
<form name="dates" id="dates" method="POST" action="">
<table cellpadding="5" border="0" width="100%">
<tr>
<td colspan="3" align="center">
<h1> select dates </h1>
</td>
</tr>
<tr>
<td width="30%" align="right">
<label for="tsmdate">Entry date </label>
</td>
<td align="left">
<input type="date" name="tsmdate" id="tsmdate" required="required">
</td>
</tr>
<tr>
<td width="30%" align="right">
<label for="tsmTime">Entry time</label>
</td>
<td align="left">
<input type="time" name="tsmTime" id="tsmTime" required="required">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="dates">
</td>
</tr>
</table>
</form>
</body>
</html>
The $presentTime is always the same as the $EntryTime. This is because you use the entry time in the date function.
Change
$presentTime= date('h:i A', strtotime($EntryTime));
to
$presentTime= date('h:i A');
Related
I created two forms, one is registration form the other is picking the dates the user will come and leave. I called the user's username in the 2nd page.. and although i receive it, i get a message "error" and nothing gets updated on my database. Here is my 2nd page file.. What am i doing wrong?
<?php
session_start();
$EntryError=$ExitError="";
if (isset($_POST['submit'])){
$entrydate = $exitdate = "";
$errorOccured = false;
if (isset($_POST['tsmdate'])){
$entrydate = trim($_POST['tsmdate']);
if (strlen($entrydate) == 0){
$EntryError = "date is missing";
$errorOccured = true;
}
}
else{
$EntryError = "date is missing";
}
// checking for last name
if (isset($_POST['tsmexit'])){
$exitdate = trim($_POST['tsmexit']);
if (strlen($exitdate) == 0){
$ExitError = "First Name is missing";
$errorOccured = true;
}
}
else{
$ExitError = "last Name is missing";
}
$ids=$_SESSION['tsmUserName'];
var_dump($_SESSION);
if(!$errorOccured){
require_once("connection.php");
$my_query="INSERT INTO timing (No, Entry Date and Time, Exit Date and Time, user_id) VALUES (NULL,'$EntryError','$exitdate','$ids')";
$result=mysqli_query($connection,$my_query);
if($result)
{
echo 'thank you';
}
else
{
echo 'error';
}
mysqli_close($connection);
}
}
?>
<html>
<head>
</head>
<body>
<form name="dates" id="dates" method="POST" action="">
<table cellpadding="5" border="0" width="100%">
<tr>
<td colspan="3" align="center">
<h1> select dates </h1>
</td>
</tr>
<tr>
<td width="30%" align="right">
<label for="tsmdate">Entry date and time</label>
</td>
<td align="left">
<input type="text" name="tsmdate" id="tsmdate" required="required">
</td>
</tr>
<tr>
<td width="30%" align="right">
<label for="tsmexit">Exit date and time</label>
</td>
<td align="left">
<input type="text" name="tsmexit" id="tsmexit" required="required">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="dates">
</td>
</tr>
</table>
</form>
</body>
</html>
Change INSERT query to this
$my_query="INSERT INTO timing (`No`, `Entry Date and Time`, `Exit Date and Time`, `user_id`) VALUES (NULL,'$EntryError','$exitdate','$ids')";
Make sure if any database field name has space in name, then it should be within ` (back tic)
Your insert query isn't a valid query because of the spaces in your column names, I suggest your change the spaces into '_' characters so you won't walk into more trouble. If you like to keep the spaces you have to escape the column names with the "`" character.
Example
$query="INSERT INTO timing (`No`, `Entry Date and Time`, `Exit Date and Time`, `user_id`) VALUES (NULL, '$EntryError', '$exitdate', '$ids')";
Your form is very vulnerable to SQL injection, to prevent this you have to escape your variables with the mysqli::real_escape_string function.
Example
$EntryError = mysqli_real_escape_string($connection, $EntryError);
$exitdate = mysqli_real_escape_string($connection, $exitdate);
$query="INSERT INTO timing (`No`, `Entry Date and Time`, `Exit Date and Time`, `user_id`) VALUES (NULL, '$EntryError', '$exitdate', '$ids')";
At present I have set 4 variables, the values of which are then stored into mysql. This works fine. However, I don't want to set the values but write a line of code that takes these values from my form (on the same page). I have set the form method to POST and added specialchars to help security. Can someone pretty please show me one or two lines of code so I don't have to write ="John Doe". Please remember that I am very new all of this
<?php
// Connect to the Database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "topsecretDontTell";
$dbname = "gaming";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Show error if connection fails
if(mysqli_connect_errno()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() .")"
);
}
?>
<?php
// ordertbl
$customer_name = "John Doe";
$game_id = 3;
$reservation_start = "2015-01-05";
$requested_days = 1;
// removes single quotes (escapes strings)
$customer_name = mysqli_real_escape_string($connection, $customer_name);
//add into ordertbl
$query = "INSERT INTO ordertbl (customer_name,game_id,reservation_start,requested_days) VALUES ('{$customer_name}',{$game_id},'{$reservation_start}', {$requested_days})";
//Run query and test if there was a query error
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed.");
}
?>
<?php
//determine the name of the game via its id using a function
function GameTitle ($game_id){
$message = "";
if ($gameid ==1){
$message = "Fantasy World";
}
else if ($gameid ==2){
$message = "Sir Wags A Lot";
}
else if ($gameid ==3){
$message = "Take a Path";
}
else if ($gameid ==4){
$message = "River Clean Up";
}
else if ($gameid ==5){
$message = "PinBall";
}
else if ($gameid ==6){
$message = "Ghost girl";
}
else if ($gameid ==7){
$message = "Dress up";
}
else if ($gameid ==8){
$message = "Where is my hat?";
}
else {
$message = "Invalid ID";
}
return $message;
}
?>
</body>
</html>
<!--Link to the style sheet-->
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<!--Create Header (logo, title and navigation bar)-->
<body>
<div id='main'>
<div id='titleImage'><img title='Home' src='images/GLLogo.png' width='700' height='190' alt='Games Library Title' /></div>
<div id='menu-wrapper'>
<div id='menu'>
<ul>
<li><a href='index.html'>Home</a></li>
<li class='current_page_item'><a href='#'>Reservations</a></li>
</ul>
</div>
</div>
<!--Make the form-->
<div class="form">
<h1>Reservations</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="755" border="3" cellpadding="6">
<tr>
<td width="195" align="right" bgcolor="#FF0000"><label for="customer_name">Name:</label></td>
<td width="370"><input name="customer_name" autofocus type="text" id="customer_name" size="35" maxlength="90" required autocomplete="off" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="game_id">Game's ID:</label></td>
<td><input name="game_id" type="number" id="game_id" size="35" maxlength="50" min="1" /></td>
</tr>
<tr>
<td width="195" align="right" bgcolor="#FF0000"><button onClick="GameTitle(); return false">Search</button></td>
<td><input name="Result" type="text" id="demo" size="35" maxlength="50" /></td>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="Loan">Number of Days you wish to borrow the Game</label></td>
<td><select name="requested_days" id="requested_days">
<option selected="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
<tr> <!--put date into value field to get a calendar-->
<td align="right" bgcolor="#FF0000"><label for="reservation">Reservation Date:</label></td>
<td><input id="reservation_start" input name="reservation_start" type="" value="" placeholder="YYYY/MM/DD" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" title="The date should be in the exact format: YYYY-MM-DD with leading zeros where necessary"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><label for="mysearch2">Enter your search string here : </label></td>
<td><input {background-colour: #E5F5EF;} id="mysearch2" type="search" placeholder="search"size="35" maxlength="50"/>
</tr>
<tr>
<td align="right" bgcolor="#FF0000"><input type="reset" name="Reset" id="button" value="Reset Form" /></td>
<td><input type="submit" name="button2" id="button2" value="Submit Form" /></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
<?php
// get rid of data in cache and close
mysqli_close($connection);
?>
Use the following, taking the POST variable from your form's <input name="customer_name"... element:
$customer_name=stripslashes($_POST['customer_name']);
$customer_name=mysqli_real_escape_string($connection,$_POST['customer_name']);
which will allow for names containing apostrophes like John O'Reilly.
Plus, you have function GameTitle ($game_id) therefore you most likely meant to use function GameTitle ($gameid)
You should use $_POST. In that array are post data. For example:
$customer_name = $_POST['name'];
<head>
<title> Add User page</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<form name='f2' action="insert_ac.php" method="post" >
<script src="validation.js" type="javascript/text"></script>
</head>
<body onload="firstfocus();">
<table align="center" border="0" cellpadding="3" cellspacing="1">
<tr>
<td> First Name</td><td > : </td>
<td> <input type='text' name='fname' id='fid' size="50" style="background-color:#abcddd; height:18px;" value='' maxlength="100" onblur="fname_validation(5,12);"> </td>
</tr>
<tr>
<td> Last Name</td><td> : </td>
<td> <input type='text' name='lname' id='lid' size="50" style="background-color:#abcddd; height:18px; "value='' maxlength="100" onblur="lname_validation(5,12);"> </td>
</tr>
<tr>
<td> Gender</td><td> : </td>
<td> <input type='radio' name='gend' id='m' value='M' checked>Male <input type='radio' name='gend' id='f' value='F'>Female</td>
</tr>
<tr>
<td> Phone Number</td><td> : </td>
<td> <input type='number_format' name='phone' id='phno'size="50" style="background-color:#abcddd; height:18px; " value=''onblur="allnumeric();"></td>
</tr>
<tr>
<td> Work Experiance</td><td> : </td>
<td><select name="exp" onblur="expselect();">
<option > Select One</option>
<option selected="" value="Default"> Select One </option>
<option value="F"> Fresher </option>
<option value="E"> Experiance</option>
</select></td>
</tr>
<tr>
<td>User Name</td><td>:</td><td> <input type='txt' name='uname' id='uid'size="50" style="background-color:#abcddd; height:18px; " value=''onblur="userid_validation(5,10);"> </td>
</tr>
<tr>
<td>Password</td><td>:</td><td> <input type='password' name='pwd' id='pid' size="50" style="background-color:#abcddd; height:18px; " value=''onblur="passid_validation(7,12);"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td width="84"><input name="enter" class="btn_login" type="submit" value="Submit" onsubmit="alert('Data stored successfully');"/> <input name="cancle" class="btn_login" type="reset" value="Cancle" /></td>
</tr>
</table>
</form>
</body>
</html>
I included the external javascript file using script tag but the validations are not working.
This is my external javascript code which was saved as validation.js and i am unable to find errors in it please help me.
// After form loads focus will go to first name field.
function firstfocus()
{
var fname = document.f2.fname.focus();
return true;
}
// This function will validate First name
function fname_validation(mx,my)
{
var fname = document.f2.fname;
var fname_len = fname.value.length;
var letters = /^[A-Za-z]+$/;
if (fname_len == 0 || fname_len >= my || fname_len < mx)
{
alert("First Name should not be empty / length be between "+mx+" to "+my);
fname.focus();
return false;
if(fname.value.match(letters))
{
// Focus goes to next field i.e.Last Name
document.f2.lname.focus();
return true;
}
}
}
// This function will validate Last name
function lname_validation(mx,my)
{
var lname = document.f2.lname;
var lname_len = lname.value.length;
var letters = /^[A-Za-z]+$/;
if (lname_len == 0 || lname_len >= my || lname_len < mx)
{
alert("Last Name should not be empty / length be between "+mx+" to "+my);
lname.focus();
return false;
if(fname.value.match(letters))
{
// Focus goes to next field i.e.Phone Number
document.f2.phone.focus();
return true;
}
}
}
// This function will validate Phone Number.
function allnumeric()
{
var phone = document.f2.phone;
var numbers = /^[0-9]+$/;
if(phone.value.match(numbers))
{
// Focus goes to next field i.e. Experiance.
document.f2.exp.focus();
return true;
}
else
{
alert('Phone Number must have numeric characters only');
phone.focus();
return false;
}
}
// This function will select Experiance.
function expselect()
{
var exp = document.f2.exp;
if(exp.value == "Default")
{
alert('Select your Experiance from the list');
exp.focus();
return false;
}
else
{
// Focus goes to next field i.e. Username Code.
document.f2.uname.focus();
return true;
}
}
// This function will validate User Name.
function allLetter()
{
var uname = document.f2.uname;
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
// Focus goes to next field i.e. Password.
document.f2.pwd.focus();
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
// This function will validate Password.
function passid_validation(mx,my)
{
var passid = document.registration.passid;
var passid_len = passid.value.length;
if (passid_len == 0 ||passid_len >= my || passid_len < mx)
{
alert("Password should not be empty / length be between "+mx+" to "+my);
passid.focus();
return false;
}
}
try to change <script type="javascript/text"> to <script type="text/javascript">
and double check the reference of your js file. Also, put an alert check to determine if it is really going through the firstFocus() function.
You have to reference the .js if its not in the same folder as html
EDIT
function fname_validation(mx,my)
{
is missing a closing bracket!
I changed the java script file and now i can find validations in my form...
Thanks for your help..
here i am sharing my code...
HTML code
<form name='f1' action="insert_ac.php" method="post" onSubmit="return validateForm();" >
<tr>
<td height="25" height="25" colspan="2" bgcolor="#EC6921" class="form_heading">Add User Form</td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> First Name:</td>
<td bgcolor="#FFFFFF"> <input type='text' name='fname' id='fid' size="50" style="height:18px;" value='' maxlength="100" ></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Last Name:</td>
<td bgcolor="#FFFFFF" > <input type='text' name='lname' id='lid' size="50" style=" height:18px; "value='' maxlength="100" ></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Gender:</td>
<td bgcolor="#FFFFFF" > <input type='radio' name='gend' id='m' value='M' checked>Male <input type='radio' name='gend' id='f' value='F'>Female</td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Phone Number:</td>
<td bgcolor="#FFFFFF" > <input type='number_format' name='phone' id='phno'size="50" style=" height:18px; " value=''></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Work Experiance:</td>
<td bgcolor="#FFFFFF" ><select name="exp" >
<option selected="" value="Default"> Select One </option>
<option value="Fresher"> Fresher </option>
<option value="Experiance"> Experiance</option>
</select></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt">User Name:</td><td bgcolor="#FFFFFF"> <input type='txt' name='uname' id='uid'size="50" style=" height:18px; " value=''></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt">Password:</td><td bgcolor="#FFFFFF"> <input type='password' name='pwd' id='pid' size="50" style=" height:18px; " value=''></td>
</tr>
</table>
<table align="center">
<tr>
<td ><input name="enter" class="btn_login" type="submit" value="Submit" align="center"><input name="cancle" class="btn_login" type="reset" value="Cancle" valign="right" /></td>
</tr>
</table>
</div>
</div>
</div>
</form>
</body>
</html>
Here is my java script file which is working fine....
var RE = /^.+#.+\..{3}$/;
var RE1 = /^[a-zA-Z]+$/;
var RE2 = /^[0-9]{10}$/;
var RE3 = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
function validateForm()
{
if (document.f1.fname.value == "")
{
window.alert("first name should NOT BE empty");
document.f1.fname.focus();
return false;
}
else
if (RE1.test(document.f1.fname.value) == false)
{
alert("Invalid first name\n\
");
return false;
}
else
if (document.f1.fname.value.length < 3)
{
window.alert("Firstname must have atleast Three characters");
document.f1.fname.focus();
return false;
}
else
if (document.f1.lname.value == "")
{
window.alert("Lastname should not be empty");
document.f1.lname.focus();
return false;
}
else
if (RE1.test(document.f1.lname.value) == false)
{
alert("Invalid last name");
return false;
}
else
if (document.f1.lname.value.length < 4)
{
window.alert("Lastname must have atleast four characters");
document.f1.lname.focus();
return false;
}
else
if (document.f1.lname.value == "")
{
window.alert("Last name should not be empty");
document.f1.lname.focus();
return false;
}
else
if (document.f1.phone.value == "")
{
window.alert("phne no should NOT BE empty");
document.f1.phone.focus();
return false;
} else
if (RE3.test(document.f1.phone.value) == false)
{
alert("Invalid phone number");
document.f1.phone.focus();
return false;
}
else
if (document.f1.exp.selectedIndex == 0)
{
window.alert("please select work experiance ");
return false;
}
else
if (document.f1.uname.value == "")
{
window.alert("UserName should not be empty");
document.f1.uname.focus();
return false;
}
else
if (RE1.test(document.f1.uname.value) == false)
{
window.alert("Invalid userName ");
document.f1.uname.focus();
return false;
}
else
if (document.f1.pwd.value == "")
{
window.alert("password should not be empty");
document.f1.pwd.focus();
return false;
}
else
if (document.f1.pwd.value.length < 6)
{
window.alert("password must have atleast six characters");
document.f1.pwd.focus();
return false;
}
else
{
window.alert("User has been added successfully.");
return true;
}
}
I wonder is it possible to keep the user input inside form field after form submitted, so that the user can update the entry. I've a html registration form [with some JS validation], then a php file to insert data to sql & meanwhile display back the inserted data in a table view. i also include the form's html code in php file so i can see the form after being submitted. but i couldn't keep the data in the field after form submitted! here is the form:
<!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>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="insert.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Submit" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
</body>
</html>
here is the insert.php file:
<!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>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="update.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Update" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
<br>
</div>
</form>
<div align="center">
<?php
if (!mysql_connect('localhost', 'root', '')) {
echo "Connected";
}
mysql_select_db("workshop");
// Get values from form
$ic = mysql_real_escape_string($_POST['ic']);
$name = mysql_real_escape_string($_POST['name']);
$contact = mysql_real_escape_string($_POST['contact']);
$mail = mysql_real_escape_string($_POST['mail']);
$address = mysql_real_escape_string($_POST['address']);
if (staff_detail_exist($ic) == "available") {
insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype);
echo "<p style='text-align:center; color:green;'>" . "Workshop application successful! You will be notified shortly via E-mail after confirmation! Thank You!";
} else if (staff_detail_exist($ic) == "exist") {
echo "<p style='text-align:center; color:red;'>" . "Record already exists! Please enter another Staff ID. Thank You!" . "</p>";
}
function insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype) {
$sql = "INSERT INTO apply (staffid, staffname, staffno, staffemail, staffaddress, paytype) VALUES ('$ic', '$name', '$contact', '$mail', '$address','$paytype')";
mysql_query($sql);
}
function staff_detail_exist($ic) {
$result = null;
$sql = "SELECT * FROM apply WHERE staffid = '$ic'";
$data = mysql_query($sql);
if (mysql_num_rows($data) == 0) {
$result = "available";
} else {
$result = "exist";
}
return $result;
}
$staffid = $_POST['ic'];
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("workshop", $con);
$result = mysql_query("SELECT * FROM apply where staffid = '$ic'");
echo "<table width=400 border=1 cellpadding=0 align=center>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<th>Staff/IC Number: </th><td>" . "<center>" . $row['staffid'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Name: </th><td>" . "<center>" . $row['staffname'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Email: </th><td>" . "<center>" . $row['staffemail'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Contact No.: </th><td>" . "<center>" . $row['staffno'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Address: </th><td>" . "<center>" . $row['staffaddress'] . "</center>" . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
I've tried to add like value="<? echo "$row['staffid']"?>" in the form's field at php file but no luck! I've only basic in php. So, any help? thank you!
thanks all, its finally working :) i've used value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" inside the input tag. so, its like: <input type="text" name="myField" value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" /> where myField is input name & myField_db is the column name from database.
Take the form posted values just above your html code like this
<?php
if (isset($_POST["submit"]) && $_POST["submit"]=='Submit') {
$name=$_POST["name"];
}
?>
And echo it in your html form.
<input name="name" type="text" id="name" size="45" value="<? echo $name?>"/>
I've used this function a few times; quite handy
function getPost($field){
return (isset($_POST[$field]) && $_POST[$field] != "" ? $_POST[$field] : "");
}
Usage
<input type="text" name="contact" value="<?php echo getPost("contact"); ?>" />
This is for the cases where a user submits information and is for some reason sent back to the form again - perhaps their entries didn't pass PHP validation, for example.
This is my code:
<?php
function GetDays($sStartDate, $sEndDate){
$sStartDate = gmdate("Y-m-d", strtotime($sStartDate));
$sEndDate = gmdate("Y-m-d", strtotime($sEndDate));
$aDays[] = $sStartDate;
$sCurrentDate = $sStartDate;
while($sCurrentDate < $sEndDate){
$sCurrentDate = gmdate("Y-m-d", strtotime("+1 day", strtotime($sCurrentDate)));
$aDays[] = $sCurrentDate;
}
return $aDays;
}
?>
<html>
<head>
<script language="JavaScript" src="calendar_us.js"></script>
<link rel="stylesheet" href="calendar.css">
</head>
<body background="mainbg.JPG">
<form action="<?=$_SERVER['PHP_SELF']?>" method="POST">
<?
//If we submitted the form
if(isset($_POST['submitMe']))
{
$sec=00;
$sc=00;
$name=$_POST['name'];
$mm=substr($_POST['testinput'],0,2);
$dd=substr($_POST['testinput'],3,2);
$yy=substr($_POST['testinput'],6,4);
$sdate = $yy."-".$mm."-".$dd;
$mn=substr($_POST['test'],0,2);
$dn=substr($_POST['test'],3,2);
$yn=substr($_POST['test'],6,4);
$edate = $yn."-".$mn."-".$dn;
$host="10.207.100.10";// Host name
$username="root";// Mysql username
$password="######"; // Mysql password
$db_name="wtems"; // Database name
$tbl_name="constellation_reserve"; // Table name // Connect to server and selectdatabse
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM constellation_reserve where CID=$name and (start_date between '$sdate' and '$edate' or end_date between '$sdate' and '$edate')";
$result=mysql_query($sql); // Define$color=1
if($result)
{
$color="1";
echo '<table border="0" cellpadding="8" align="center">';
echo'<tr>';
echo'</tr>';
echo'<tr>';
echo'</tr>';
echo '<tr><h3 align="center"<font color="white">RESERVATION </font></h3></tr>';
echo'<tr>';
echo'</tr>';
echo'<tr>';
echo '<table width="500" height="300" border="0" align="center" cellpadding="8" cellspacing="2">';
$fields_num = mysql_num_fields($result);
echo "<tr bgcolor='#0099FF'>";
echo "<td><FONT COLOR='FFFFFF'>ID</FONT> </td>";
echo "<td><FONT COLOR='FFFFFF'>START DATE</FONT></td>";
echo "<td> <FONT COLOR='FFFFFF'>RESERVED BY </FONT></td>";
echo "<td><FONT COLOR='FFFFFF'>END DATE</FONT></td>";
echo "</tr>\n";
while($rows=mysql_fetch_array($result))
{ // If $color==1 table row color = #FFC600
if($color==1)
{
echo "<tr bgcolor='#FFFFDD'>
<td>".$rows['CID']."</td><td>".$rows['start_date']."</td><td bgcolor='#99AAFF'><FONT COLOR='FFFFFF'>".$rows['owner']."</FONT></td><td>".$rows['end_date']."</td></tr>";
// Set$color==2, for switching to other color
$color="2";
} // When$color not equal 1, use this table row color
else
{
echo "<tr bgcolor='#FFFFEE'><td>".$rows['CID']."</td><td>".$rows['start_date']."</td><td bgcolor='#99AAFF'><FONT COLOR='FFFFFF'>".$rows['owner']."</FONT></td><td>".$rows['end_date']."</td></tr>";// Set $color back to 1
$color="1";
}
}
echo '</table>';
mysql_close();
echo '</tr>';
echo '</table>';
}
else
{
echo '<table border="0" cellpadding="8" align="center">';
echo '<tr><h3 align="center"<font color="white">NoDataFound</font></h3></tr>';
echo '</table>';
}
}
//If we haven't submitted the form
else
{
?>
<h3 align="center"<font color="white">REPORT DETAILS</font></h3>
<table border="1" cellpadding="8" align="center">
<br>
</br>
<tr><td align="left">Constellation ID</td><td>:</td><td> <input type="text" name="name" /></td></tr>
<tr><td align="left">Start Date</td><td>:</td><td> <input type="text" name="testinput" />
<script language="JavaScript">
new tcal ({
// form name
//'formname': 'testform'
// input name
'controlname': 'testinput'
});
</script>
</td></tr>
<tr><td align="left">End Date</td><td>:</td><td> <input type="text" name="test" />
<script language="JavaScript">
new tcal ({
// form name
//'formname': 'testform'
// input name
'controlname': 'test'
});
</script>
</td></tr>
</table>
<br>
</br>
<br>
</br>
<p align="center"><input type="submit" value="REPORT" name="submitMe"></p>
<?php
}
?>
</form>
</body>
</html>
when i execute the code is working fine but, the datas are not displaying in the same page.
when the data are displaying the page is refreshing so i cant view the data in same page.
You should never use a root username and password when you are developing an app, create an account and use, when you post remove it.
The issue has to be coming from your JavaScript if your page refreshes after loading. PHP is a server side language, meaning it can redirect before user output but not after. Post your JS or a link to the page here so we can help more.
Seconding #ProNeticas -- NEVER ever use your root password when you are developing an app.
Also your code is open to SQL injection -- please read about mysql_real_escape_string
#user.. i just format your code... please look and apply... then we'll discuss on your problem...
<?php
function GetDays($sStartDate, $sEndDate){
$sStartDate = gmdate("Y-m-d", strtotime($sStartDate));
$sEndDate = gmdate("Y-m-d", strtotime($sEndDate));
$aDays[] = $sStartDate;
$sCurrentDate = $sStartDate;
while($sCurrentDate < $sEndDate){
$sCurrentDate = gmdate("Y-m-d", strtotime("+1 day", strtotime($sCurrentDate)));
$aDays[] = $sCurrentDate;
}
return $aDays;
}
?>
<html>
<head>
<script type="javascript" src="calendar_us.js"></script>
<link rel="stylesheet" href="calendar.css" >
</head>
<body background="mainbg.JPG">
<form action="<?=$_SERVER['PHP_SELF']?>" method="POST">
<?
//If we submitted the form
if(isset($_POST['submitMe']))
{
$sec=00;
$sc=00;
$name=$_POST['name'];
$mm=substr($_POST['testinput'],0,2);
$dd=substr($_POST['testinput'],3,2);
$yy=substr($_POST['testinput'],6,4);
$sdate = $yy."-".$mm."-".$dd;
$mn=substr($_POST['test'],0,2);
$dn=substr($_POST['test'],3,2);
$yn=substr($_POST['test'],6,4);
$edate = $yn."-".$mn."-".$dn;
$host="#######";// Host name
$username="#####";// Mysql username
$password="######"; // Mysql password
$db_name="####"; // Database name
$tbl_name="constellation_reserve"; // Table name // Connect to server and selectdatabse
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM constellation_reserve where CID=$name and (start_date between '$sdate' and '$edate' or end_date between '$sdate' and '$edate')";
$result=mysql_query($sql); // Define$color=1
$fields_num = mysql_num_fields($result);
if($result)
{ ?>
<table border="0" cellpadding="8" cellspacing="5" align="center">
<tr>
<td><h3 align="center"<font color="white">RESERVATION </font></h3></td>
</tr>
<tr>
<td>
<table width="500" height="300" border="0" align="center" cellpadding="8" cellspacing="2">
<tr style="color:#fff;background-color:#0099FF">
<td>ID</td>
<td>START DATE</td>
<td>RESERVED BY</td>
<td>END DATE</td>
</tr>
<?php
while($rows=mysql_fetch_array($result))
{ $color=1;
// If $color==1 table row color = #FFC600
if($color == 1){ ?>
<tr background-color='#FFFFDD'>
<td><?php echo $rows['CID']?></td>
<td><?php echo $rows['start_date'];?></td>
<td style="color:#FFF;background-color:#99AAFF'><?php echo $rows['owner'];?></td>
<td><?php echo $rows['end_date']?></td>
</tr>
<?php $color=2;
} else { ?>
<tr background-color='#FFFFEE'>
<td><?php echo $rows['CID'];?></td>
<td><?php echo $rows['start_date'];?></td>
<td style="color:#FFF;background-color:#99AAFF'><?php echo $rows['owner'];</td>
<td><?php echo $rows['end_date'];?></td>
</tr>
<?php $color=1;
}
} ?>
</table>
<?php mysql_close(); ?>
</td>
</tr>
</table>
<?php } else { ?>
<table border="0" cellpadding="8" align="center">
<tr><h3 align="center"style="color:#fff">NoDataFound</h3></tr>
</table>
<?php }
} //If we haven't submitted the form
else { ?>
<h3 align="center"<font color="white">REPORT DETAILS</font></h3>
<table border="1" cellpadding="8" align="center">
<tr>
<td align="left">Constellation ID</td>
<td>:</td>
<td> <input type="text" name="name" /></td>
</tr>
<tr>
<td align="left">Start Date</td>
<td>:</td>
<td> <input type="text" name="testinput" />
<script type="javascript">
new tcal ({
// form name
//'formname': 'testform'
// input name
'controlname': 'testinput'
});
</script>
</td>
</tr>
<tr>
<td align="left">End Date</td>
<td>:</td>
<td> <input type="text" name="test" />
<script typr"javascript">
new tcal ({
// form name
//'formname': 'testform'
// input name
'controlname': 'test'
});
</script>
</td>
</tr>
</table>
<p align="center"><input type="submit" value="REPORT" name="submitMe"></p>
<?php } ?>
</form>
</body>
</html>