<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;
}
}
Related
When i provide value in any one field of form and click on ragister it gets submitted but should not submit till the all field get filled what i am doing wrong please let me know, as I have taken pre tag at the top where i can see all the values that i'm getting when i click on ragister.
<?php
$error_array = array();
$fname = $lname = $email = $dob = $Mchecked = $Fchecked = $hobbies ="";
if(isset($_GET["sbt_save"]))
{
echo '<pre>'; print_r($_GET); echo "</pre>";
if($_GET['fname']=="")
{
$err ="Please Enter your first name"."<br>";
array_push($error_array,$err);
}
else
{
$fname = test_input($_GET['fname']);
}
if($_GET['lname']=="")
{
$err ="Please Enter your last name"."<br>";
array_push($error_array,$err);
}
else
{
$lname = test_input($_GET["lname"]);
}
if($_GET['email']=="")
{
$err ="Please Enter your email"."<br>";
array_push($error_array,$err);
}
else
{
$email = test_input($_GET["email"]);
}
if($_GET['dob']=="")
{
$err ="Please Enter your date of birth"."<br>";
array_push($error_array,$err);
}
else
{
$dob = test_input($_GET["dob"]);
}
if(!isset($_GET["gender"]))
{
$err ="Please select gender"."<br>";
array_push($error_array,$err);
}
else
{
$gender = $_GET["gender"];
if ($gender == "Male")
{
$Mchecked = "checked";
}
else if ($gender == "Female")
{
$Fchecked = "checked";
}
}
if(!isset($_GET['hobbies']))
{
$err ="Please Enter your hobbies"."<br>";
array_push($error_array,$err);
}
else
{
$hobbies = test_input($_GET['hobbies']);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!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" />
<title>Ragistration Form</title>
<link rel="stylesheet" type="text/css" href="ragistration_form.css">
<!--
<script src="jquery-2.2.1.min.js"></script>
<script>
$(document).ready(function(event)
{
$(".sbt_button").click(function(event)
{
var error_arr = [];
var email_value = $("#email").val();
var position_of_at = email_value.indexOf('#');
var position_of_dot = email_value.lastIndexOf('.');
if($("#fname").val() == null || $("#fname").val() == "")
{
var err = "First Name";
error_arr.push(err);
}
if($("#lname").val() == null || $("#lname").val() == "")
{
var err = "Last Name ";
error_arr.push(err);
}
if(position_of_at == -1 || position_of_dot == -1 || (position_of_at + 2) >= position_of_dot )
{
var err = "Email ";
error_arr.push(err);
}
if($("#dob").val() == null || $("#dob").val() == "")
{
var err = "Date of Birth ";
error_arr.push(err);
}
if(!$("input[type='radio']").is(":checked"))
{
var err = "Gender ";
error_arr.push(err);
}
if(!$("input[type='checkbox']").is(":checked"))
{
var err = "Hobbies ";
error_arr.push(err);
}
if(error_arr.length !=0)
{
event.preventDefault();
alert(error_arr);
}
});
});
</script>
-->
</head>
<body>
<form class="form" name="myForm" action="" method="GET">
<table>
<tr>
<p class="heading">Ragistration Form</p>
</tr>
<?php
if($error_array !="")
{
foreach($error_array as $value)
{
echo "<tr style='color:red;'><td> ". $value. "</td></tr>";
}
}
?>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td class="field_Name">First Name :<b style="color:red">*</b></td>
<td><input type="text" name="fname" id="fname" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Last Name :<b style="color:red">*</b></td>
<td><input type="text" name="lname" id="lname" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Email :<b style="color:red">*</b></td>
<td><input type="text" name="email" id="email" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Date of Birth :<b style="color:red">*</b></td>
<td><input type="date" name="dob" id="dob" class="inputfield_Name" /></td>
</tr>
<tr>
<td class="field_Name">Gender :<b style="color:red">*</b></td>
<td><input type="radio" name="gender" value="Male"class="inputfield_Name" <?php echo $Mchecked;?> />
Male
<input type="radio" name="gender" value="Female" <?php echo $Fchecked;?> />
Female</td>
</tr>
<tr>
<td class="field_Name">About Yourself :</td>
<td><textarea name="abt" class="inputfield_Name"$></textarea></td>
</tr>
<tr>
<td class="field_Name">Hobbies :<b style="color:red">*</b></td>
<td><input name="hobbies" value="Cricket" type="checkbox" id="hobbies" class="inputfield_Name" />
Cricket
<input name="hobbies" value="Singing" type="checkbox" />
Singing
<input name="hobbies" value="Travling" type="checkbox" />
Travling</td>
<tr>
<td></td>
<td><input name="hobbies" value="Writing" type="checkbox" class="inputfield_Name" />
Writing
<input name="hobbies" value="Teaching" type="checkbox" />
Teaching
<input name="hobbies" value="Driving" type="checkbox" />
Driving </td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Ragister" name="sbt_save" class="sbt_button"/></td>
</td>
</tr>
</table>
</form>
</body>
</html>
I have tried your code, its working fine. See the below screenshot.
If you want to validate your form before submit then use the commented javascript/client-side validation and if you want to validate it afterwards then use your php/server-side validation.
Let me know if you are facing any other problem.
I have a php script that ask the user to upload a csv, then it display the result before importing and ask the user to map the fields corresponding to the database tables. It work fine.
My problem is that it seems that the server restrict the number of post or insert that can be made. So I can insert like 75 lines. But I have something like 600 lines. How could I split those like maybe in different files or maybe INFILE function.
I'm a little bit loss on that one. Because also, the user can select wich record he wants to be inserted with checkboxes.
<?php
setlocale(LC_ALL,"en_US.UTF-8");
ob_start();
if(!isset($_SESSION))
{
session_start();
}
//variables
$upload_file='';
$err='';
$msg='';
include "config.php";
if(isset($_POST['frm_type'])) // Insert Records
{
if(isset($_POST['frm_type']) && $_POST['frm_type']=='custom')
{
if(count($_POST["chk"])>0)
{
$count_cols=$_POST["h_cols"];
foreach($_POST["chk"] as $index)
{
$query="";
$dyn_query="";
$select_where="";
$date_reg=date('Y-m-d');
//STATIC COLUMN
$query = "cat_id='".$_POST["cat_id".$index]."'";
$query .= ",date_reg='".$date_reg."'";
$query .= ",user_id='".$_SESSION['user_id']."'";
$query .= ",type_client='".$_SESSION['cltype']."'";
$query .= ",birthday_switch='1',";
//DYNAMIC COLUMN
for($s=0; $s<$count_cols;$s++)
{
if(isset($_POST["colum_".$s]) && $_POST["colum_".$s]!='')
{
$value=Add_Slashes($_POST["row_".$s."_".$index]);
$dyn_query[]="".$_POST["colum_".$s]."='".$value."'";
}
if($_POST["colum_".$s]=="full_name")
{
$value=trim($_POST["row_".$s."_".$index]);
if($value!="")
{
$allow=1;
}
else
{
$allow=0;
}
}
}
if($dyn_query)
{
if($allow==1)
{
$query .=implode(',',$dyn_query);
$select_where[]="cat_id='".$_POST["cat_id".$index]."'";
$select_where[]="user_id='".$_SESSION['user_id']."'";
$select_where[]="type_client='".$_SESSION['cltype']."'";
for($t=0; $t<$count_cols;$t++)
{
if(isset($_POST["colum_".$t]) && $_POST["colum_".$t]!='')
{
$value=Add_Slashes($_POST["row_".$t."_".$index]);
$select_where[]="".$_POST["colum_".$t]."='".$value."'";
}
}
$select_where_query=implode(' AND ', $select_where);
$re = mysql_query("Select cat_id From clients Where $select_where_query");
if(mysql_num_rows($re)==0)
{
mysql_query("Insert Into clients Set $query");
$msg = "<span class='error' style=\"color:green;\"><b>Data Successfully Imported Into The Database</b></span>";
}
else
{
$msg = "<span class='error' style=\"color:red;\"><b>Data Already Existed in Database</b></span>";
}
}
}
else
{
$msg = "<span class='error' style=\"color:red;\"><b>Please select fields!</b></span>";
}
}
if(file_exists($_SESSION["FILENAME"]))
unlink($_SESSION["FILENAME"]);
}
}
}
if(isset($_POST['submt']))
{
if($_FILES['filename']["name"]=="")
$err = "<span class='error'>".IMPORT_PLEASE."</span>";
elseif(substr(strrev($_FILES['filename']["name"]),0,3)!="vsc")
$err = "<span class='error'>".IMPORT_INVALID."</span>";
else
{
$_SESSION['cltype']=$_POST['cltype'];
set_time_limit(0);
if(file_exists($Upload_Path.$_FILES['filename']["name"]))
$filename = GetRandomString(6).$_FILES['filename']["name"];
else
$filename = $_FILES['filename']["name"];
if(move_uploaded_file($_FILES['filename']["tmp_name"],$Upload_Path.$filename))
{
$upload_file = $Upload_Path.$filename;
$_SESSION["FILENAME"] = $upload_file;
}
else
$err = "<span class='error'>".IMPORT_FAIL."</span>";
set_time_limit(30);
}
}
?>
<script>
function Check_All2(obj,arr)
{
if(obj.checked)
{
var i=document.cfrm.elements.length;
var j;
for(j=0;j<i;j++)
{
if(document.cfrm.elements[j].name==arr)
document.cfrm.elements[j].checked=true;
}
}
else
{
var k=document.cfrm.elements.length;
var l;
for(l=0;l<k;l++)
{
if(document.cfrm.elements[l].name==arr)
document.cfrm.elements[l].checked=false;
}
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery('#cfrm').submit(function(event) {
colums = jQuery('select.colum');
var arr = new Array();
var h_status=false;
colums.each(function()
{
var el=jQuery(this).val();
if(el!='')
{
h_status=true;
if(jQuery.inArray(el,arr)>-1)
{
event.preventDefault();
jQuery(this).css("border","2px solid red");
alert("Duplicated Fields!");
jQuery(this).focus();
return false;
}
else
{
arr.push(el);
jQuery(this).css("border","");
}
}
});
chks = jQuery('.chk');
chks.each(function()
{
if (jQuery(this).is(':checked'))
{
h_cols=jQuery('#h_cols').val();
var mand=1;
for(var k=0; k<=h_cols; k++)
{
colum_id='#colum_'+k;
colum_value=jQuery(colum_id).val();
flel_object=jQuery('#row_'+k+'_'+jQuery(this).val());
flel_value=jQuery('#row_'+k+'_'+jQuery(this).val()).val();
if(colum_value=='full_name')
{
if(flel_value=='')
{
event.preventDefault();
alert('Enter Full Name');
flel_object.focus();
return false;
}
}
else if(colum_value=='aaa')
{
if(flel_value=='')
{
event.preventDefault();
alert('Enter Email');
flel_object.focus();
return false;
}
}
}
}
});
if(!h_status)
{
event.preventDefault();
alert('Select Any Field To Insert!');
return false;
}
});
});
</script>
<script type="text/javascript" src="ajaxsublistgenerator.js"></script>
<table class="sub" height="20px" width="100%" border="0" cellpadding="0" cellspacing="0" align="center"></table>
<table width="99%" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<td>
<fieldset>
<?
if($upload_file=="")
{
?>
<legend style="font-size:12px; font-weight:bold"><?=IMPORT_CSV;?></legend>
<form name="frm" action="" method="post" enctype="multipart/form-data">
<table width="45%" border="0" cellpadding="4" cellspacing="4" align="center">
<?
if($err!="" || $msg!="")
{
?>
<tr><td colspan="2"><?=($err!="") ? $err : $msg?></td></tr>
<?
}
?>
<tr>
<td width="30%" align="left" valign="middle"><b><?=IMPORT_FILE;?></b></td>
<td width="70%" align="left" valign="middle">
<input name="filename" id="filename" type="file" size="25" />
</td>
</tr>
<tr>
<td width="30%" align="left" valign="middle"><b><?=IMPORT_SECTION;?></b></td>
<td width="70%" align="left" valign="middle">
<select name="cltype" id="cltype">
<option value="Client">Clients</option>
<option value="prospect">Leads</option>
<option value="Contacts">Contacts</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td align="left" valign="middle">
<input name="submt" type="submit" value="<?=IMPORT_UPLOAD;?>">
</td>
</tr>
</table>
</form>
<script>document.getElementById("filename").focus();</script>
<?
}
else
{
?>
<legend style="font-size:12px; font-weight:bold"><?=IMPORT_CONTENT;?></legend>
<form name="cfrm" id="cfrm" action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="frm_type" id="frm_type" value="custom">
<div style="overflow:auto;width:100%;">
<table border="0" cellspacing="4" cellpadding="4" align="center" width="100%">
<tr>
<td width="5%" align="center">
<input onClick="javascript:Check_All2(this,'chk[]')" type="checkbox" checked="checked">
</td>
<td width="10%" align="center"><b><?=IMPORT_CAT;?></b></td>
<?php
$fd_header = fopen ($upload_file, "r");
$buffer_header = fgetcsv($fd_header, 100000, ',');
//print_r(count($buffer_header));
for($r=0; $r<count($buffer_header);$r++)
{
?>
<td width="10%" align="center">
<select class="colum" name="colum_<?php echo $r;?>" id="colum_<?php echo $r;?>">
<option value="">--Select Field--</option>
<option value="full_name">Name</option>
<option value="address">Address</option>
<option value="city">City</option>
<option value="state">Province</option>
<option value="zip">Code Postal</option>
<option value="country">Country</option>
<option value="home_phone">Tel(Home)</option>
<option value="work_phone">Tel(Work)</option>
<option value="cell_phone">Tel(Mobile)</option>
<option value="email">Email</option>
<option value="conjoint">Joint</option>
<option value="notes">Notes</option>
<option value="birthday">Birthday</option>
</select><input type="hidden" id="h_cols" name="h_cols" value="<?php echo count($buffer_header); ?>" />
</td>
<?php } ?>
</tr>
<?
$fd = fopen ($upload_file, "r");
$i=1;
while (!feof ($fd))
{
$buffer_header = fgetcsv($fd, 100000, ',');
?>
<tr>
<td align="center"><input class="chk" type="checkbox" value="<?=$i?>" name="chk[]" checked="checked" /></td>
<td align="left" ><?php $sql_cat_names = mysql_query("select * from clients_cat where user_id='".$_SESSION['user_id']."' order by cat_name") ;?>
<select class="ann_select" name="cat_id<?=$i?>" id="cat_id<?=$i?>">
<?php while($row_cat_names = mysql_fetch_array($sql_cat_names)){?>
<option value="<?=$row_cat_names['id']?>"><?=$row_cat_names['cat_name']?></option>
<?php } ?>
</select>
</td>
<?php
for($v=0; $v<count($buffer_header);$v++)
{
?>
<td align="center">
<input type="text" value="<?=$buffer_header[$v]?>" name="row_<?=$v?>_<?=$i?>" id="row_<?=$v?>_<?=$i?>" />
</td>
<?php } ?>
</tr>
<?php
$i++;
unset($buffer_header);
}
fclose ($fd);
?>
<tr>
<td colspan="7" align="center">
<input name="Submit" id="Submit" type="submit" value="Submit" />
</td>
</tr>
</table>
</div>
</form>
<?php
}
?>
</fieldset>
</td>
</tr>
</table>
You may insert multiple values in an only insert, and reduce the DDBB load.
In your PHP code, you receive the values, and make a foreach to insert each row one by one. What you should have to do is change your one by one insert to a multiple to one insert.
You're doing:
INSERT INTO table (field1, field2) VALUES ( 'value1', value2');
INSERT INTO table (field1, field2) VALUES ( 'value3', value4');
INSERT INTO table (field1, field2) VALUES ( 'value5', value6');
That gives you 3 connection to database, 3 inserts. Your query should be:
INSERT INTO table (field1, field2) VALUES ( 'value1', value2'), ('value3, 'value4'), ('value5', 'value6');
That gives you 1 connection to database, 3 inserts. Same result, less load.
UPDATE
To accomplish it in your code, you must create a string inside of your foreach with the data you want to insert: Validate the fields, create the string, and then insert them into the DDBB with an insert sentence that is out of your foreach. It's going to be a mess if I try to do it without running the script to check everything goes well, so I can only point you in the way to do the job.
Basically I have a page that displays a seating plan using check boxes. These check boxes can be ticked to represent the seat being booked. I also have a text input where names are entered for the bookings, these forms are then posted to the next page to work out what check boxes are selected and save them in the database. This is some of the code:
title>School Hall</title>
<script>
function confirmReservation() {
var selectedList = getSelectedList('Confirm Reservation');
if (selectedList) {
if (confirm('Do you want to CONFIRM this Reservation : ' + selectedList + '?')) {
document.forms[0].statusA.value=0;
document.forms[0].statusB.value=1;
document.forms[0].previousPage.value='schoolHall';
document.forms[0].action='bookingQueries.php';
document.forms[0].submit();
} else {
clearSelection();
}
}
}
function cancelReservation() {
var selectedList = getSelectedList('cancel Reservation');
if (selectedList) {
if (confirm('Do you want to CANCEL this Reservation : ' + selectedList + '?')) {
document.forms[0].statusA.value=1;
document.forms[0].statusB.value=0;
document.forms[0].previousPage.value='schoolHall';
document.forms[0].action='bookingQueries.php';
document.forms[0].submit();
} else {
clearSelection();
}
}
}
function getSelectedList(actionSelected) {
// get selected list
var obj = document.forms[0].elements;
var selectedList = '';
for (var i = 0; i < obj.length; i++) {
if (obj[i].checked && obj[i].name == 'seats[]') {
selectedList += obj[i].value + ', ';
}
}
// no selection error
if (selectedList == '') {
alert('Please select a seat ');
return false;
} else {
return selectedList;
}
}
function validateForm()
{
var x=document.forms["0"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body topmargin="0" leftmargin="0" rightmargin="0" >
<table>
<tr><td width="100%" align="left" id='table-2'>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="previousPage" value=""/>
<input type="hidden" name="statusA" value=""/>
<input type="hidden" name="statusB" value=""/>
</tr>
<table>
<tr><td width="100%" align=left" id='table-2'>
<INPUT Type="BUTTON" VALUE="Home Page" ONCLICK="window.location.href='/final/homePage.php'" align='lef'>
<INPUT Type="BUTTON" VALUE="Bookings" ONCLICK="window.location.href='/final/schoolHallBookings.php'">
<?php
// Connection
$con = mysql_connect("localhost","root","");
if(!con)
{
die('Could not connect:' . mysql_error());
}
mysql_select_db("systemDatabase",$con); // Connection to DB
echo '<br>';
echo '<font face="Trebuchet MS" color="Black" size="9" >School Hall </font>';
$query = "SELECT * from schoolHall order by rowId, columnId"; // Create Select Query
$result = mysql_query($query); // Retrieve all data from query and hold in $result
$prevRowId = null;
$seatColor = null;
$tableRow = false;
echo "<table align='center' id='table-2'"; // Create table
while (list($rowId, $columnId, $status, $updatedby, $firstName, $lastName) = mysql_fetch_row($result)) // Itterates through fetched data
{
if ($prevRowId != $rowId)
{
if ($rowId != 'A')
{
echo "</tr></table></td>";
echo "\n</tr>";
}
$prevRowId = $rowId;
echo "\n<tr><td align='center'><table class='center' border='1' cellpadding='15' cellspacing='8' align='center' id='table-2' ><tr>";
}
else
{
$tableRow = false;
}
if ($status == 0)
{
$seatColor = "lightgreen"; // Available
}
else
{
$seatColor = "red"; // Booked
}
echo "\n<td bgcolor='$seatColor' align='center'>";
echo "$rowId$columnId";
if ($status == 0 || ($status == 1)) {
echo "<input type='checkbox' name='seats[]' value='$rowId$columnId' align='center'></checkbox>"; // Create Checkboxes giving value RowId, ColumnId
}
}
echo "</tr></table></td>";
echo "</tr>";
echo "</table>";
// Con close
mysql_close();
?>
<table width='100%' border='0'>
<tr><td align='right'>
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
</td>
<td><td align='left'>
</td>
<td><td align ='right'>
<input type='button' value='Confirm Reservation' onclick='confirmReservation()'/>
</td></tr>
<tr>
<td><td align='left'>
</td>
<td><td align='left'>
</td>
<td align='right'>
<input type='button' value=' Cancel Reservation' onclick='cancelReservation()'>
</td>
</table>
</td></tr>
<tr><td width="100%" align="center">
</td></tr>
<tr><td> </td></tr>
<tr><td width="100%" align="center">
<table border="1" cellspacing="6" cellpadding="4" align="center">
<tr>
<td bgcolor='lightgreen'>Available</td>
<td bgcolor='red'>Unavailable</td>
</tr>
</table>
</td></tr>
<tr><td> </td></tr>
<tr><td width="100%" align="center">
</td></tr>
</table>
</body>
Is there any way i can incorporate validation with my current code? I need the names text checked to make sure there is actually a name entered. This needs to happen before the next page is accessed. Any ideas?
Try first add ids to your text input:
<table width='100%' border='0'>
<tr>
<td align='right'>
First Name: <input type="text" id="fname" name="fname"/>
Last Name: <input type="text" id="lname" name="lname"/>
</td>
<td>
<td align='left'>
function getSelectedList(actionSelected) {
// get selected list
var obj = document.forms[0].elements;
var selectedList = '';
for (var i = 0; i < obj.length; i++) {
if (obj[i].checked && obj[i].name == 'seats[]') {
selectedList += obj[i].value + ', ';
}
}
var fname = document.getElementById('fname');
var lname = document.getElementById('lname');
// no selection error
if (selectedList == '') {
alert('Please select a seat ');
return false;
} else if (actionSelected.beginsWith('Confirm') && (fname .value.replace(/^\s+|\s+$/g, '').length == 0 || /[0-9]/.test(fname))) {
alert('Please Enter valid first name.');
return false;
} else if (actionSelected.beginsWith('Confirm') && (lname.value.replace(/^\s+|\s+$/g, '').length == 0 || /[0-9]/.test(lname))) {
alert('Please Enter valid last name.');
return false;
} else {
return selectedList;
}
}
Working example
http://jsfiddle.net/
The below example demonstrates how you can pass a value to the function checkInput and it will determine whether or not it is a valid input - the function uses jQuery but you can do it whthout jQuery too.
Demo HTML:
<form>
<input id="first-name" value="some value" />
<input id="last-name" value="" />
</form>
JS Function (goes with HTML demo):
function checkInput(fieldID){
var isValid = true;
if($("#" + fieldID).val() == ''){
isValid = false;
}
return isValid;
}
$(document).ready(function(){
if(!checkInput("first-name")){
alert("error found with first name");
}
if(!checkInput("last-name")){
alert("error found with last name");
}
});
in this code,error message shows error by alert box,but i want to see error message below particular text box. mean when i click on submit button which field not fill, below that field it should display message below that field.
and also there is one problem if i not fill radio button or checkbox and other all are filled and when i click on submit button it store in database other all detail except that radio or checkbox.
so how can i solve it
Thanks.....
<!DOCTYPE html>
<?php
session_start();
if (!isset($_SESSION['txt_user'])) {
header('Location: Login.php');
}
?>
<html>
<head>
<title> Form with Validation </title>
<script language="JavaScript">
var file_selected = false;
var file_selected1 = false;
function validform()
{
var x=document.forms["form1"]["tname"].value;//Name
var y=document.forms["form1"]["address"].value;//Address
var psel=document.getElementById('fp'); //Favourite place
var valid = false;
for(var i = 0; i < psel.options.length; i++) {
if(psel.options[i].selected) {
valid = true;
break;
}
}//Favourite place
if (x==null || x=="")
{
alert("Please Enter Name:");
//flag = 0;
}
if (y==null || y==" ")
{
alert("Please Enter Address");
}
if ((form1.gender[0].checked == false) && (form1.gender[1].checked == false))
{
alert("Pleae Select Gender");
}
if (form1.hobby.checked == false && form1.hobby.checked == false && form1.hobby.checked == false)
{
alert ('Please!!!, Select any hobby!');
}
if(valid==false)
{
alert("Please! Select Any Favourite Place ");
}
if(!file_selected)
{
alert('Please Select any Picture');
}
if(!file_selected1)
{
alert('Please Select any Document');
return false;
}
{
document.getElementById('data_form').action = "Data_con.php";
return false;
}
return false;
}
function Logout()
{
document.getElementById('data_form').action = "Logout.php";
}
</script>
</head>
<body>
<!--onsubmit="return validform()"-->
<form id="data_form" name="form1" method="post" enctype="multipart/form-data" action="">
<table align="center" border="2">
<tr>
<td>Name:</td>
<td><input type="text" name="tname"></td>
</tr>
<tr>
<td>Address:</td>
<td><textarea rows="3" cols="16" name="address"> </textarea> </td>
</tr>
<tr>
<td>Gender:</td>
<td> <input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
</td>
</tr>
<tr>
<td>Hobby:</td>
<td>
<input type="checkbox" name="hobby" value="hockey"> Hockey
<input type="checkbox" name="hobby" value="reading"> Reading<br>
<input type="checkbox" name="hobby" value="traveling"> Traveling
<br>
</td>
</tr>
<tr>
<td>Country: </td>
<td>
<select name="helo">
<option value="germany">Germany </option>
<option value="india" selected>India </option>
<option value="japan">Japan </option>
</select>
</td>
</tr>
<tr>
<td>Favourite Place:</td>
<td>
<select id="fp" name="place" multiple="multiple">
<option value="ahmedabad">Ahmedabad</option>
<option value="nadiad">Nadiad</option>
<option value="anand">Anand</option>
<option value="vadodara">Vadodara</option>
<option value="surat">Surat</option>
</select>
</td>
</tr>
<tr>
<td>Photo:</td>
<td><input type="file" onchange="file_selected=true;" name="pic" ></td>
</tr>
<tr>
<td>Resume:</td>
<td><input type="file" onchange="file_selected1=true;" name="doc" ></td>
</tr>
<tr>
<td colspan="2"><center>
<input type="submit" value="Submit" Name="Submit" onclick="validform();">
<input type="submit" value="Logout" Name="Submit" onclick="Logout();">
<center></td>
</tr>
</table>
</form>
</body>
</html>
you first create tds with different id's for each and every input field
instead of alert
document.getElementById('td id').innerHTML="your message";
return false;
like this
<tr>
<td>Favourite Place:</td>
<td>
<select id="fp" name="place" multiple="multiple">
<option value="ahmedabad">Ahmedabad</option>
<option value="nadiad">Nadiad</option>
<option value="anand">Anand</option>
<option value="vadodara">Vadodara</option>
<option value="surat">Surat</option>
</select>
</td>
<td id="fp_error"></td>
</tr>
and in javascript
document.getElementById('fp_error').innerHTML="your message";
return false;
download jquery.js and jquery.validate.js and validate form elements using below demo code.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"> </script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.validate.js"> </script>
<script>
$('document').ready(function() {
$('#data_form').validate({
rules: {
'tname': {
required: true
},
'address': {
required: true
}
},
messages:{
'tname': {
required: 'Please Enter Name'
},
'address': {
required: 'Please Enter address'
}
}
});
});
</script>
It is better way. Easy of implementation and also saves time.
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.