How to validate a form in php? - php

I know how to validate a form in JavaScript, but not in php.
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Cafeteria Ordering System</title>
<style type="text/css">
#import "cafeteriastyle.css";
</style>
</head>
<body>
<?php
if(isset($_POST['btnSubmit']))
{
//2nd page
}
else
{
?>
<form name="form1" method="post">
<table width="500" border="0" align="center" class="TableBorder">
<tbody>
<tr>
<td colspan="2" align="center" class="TableTitle TableHeadingFill">Cafeteria Ordering System</td>
</tr>
<tr>
<td width="250" align="right"><p>Customer ID</p></td>
<td><input type="text" name="txtID"></td>
</tr>
<tr>
<td align="right"><p>Num. Of Items Order</p></td>
<td><input type="text" name="txtItems"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btnSubmit"></td>
</tr>
</tbody>
</table>
</form>
<?php
}
?>
</body>
</html>
I have a form call "form1", inside the form1, I have 2 textfield.
When the Submit button is clicked, I want to perform a form validation check, to make sure the both textfield is filled, and jump to the 2nd page. If textfield is empty, display a alert message and stay on the same page.
I know how to do it with JavaScript, for example:
<script language="javascript" type="text/javascript">
function formValidation()
{
if(form1.elements["Name"].value.trim() == "")
{
alert("Please enter the name");
form1.elements["Name"].select();
return false;
}
return true;
}
</script>
and just need to add onSubmit="return formValidation" into the form tag like:
<form name="form1" method="post" onSubmit="return formValidation()"> then it will working probably. But how to do that with php instead of JS?

<?php
if(isset($_POST['btnSubmit']))
{
$txnid=trim($_POST['txtID']);
$txtItems=trim($_POST['txtItems']);
if(!empty($txnid) && !empty($txtItems))
{
//2nd page
}
else
{
echo 'Both Fields are Required.';
}
}
else
{
?>
<form name="form1" method="post">
<table width="500" border="0" align="center" class="TableBorder">
<tbody>
<tr>
<td colspan="2" align="center" class="TableTitle TableHeadingFill">Cafeteria Ordering System</td>
</tr>
<tr>
<td width="250" align="right"><p>Customer ID</p></td>
<td><input type="text" name="txtID"></td>
</tr>
<tr>
<td align="right"><p>Num. Of Items Order</p></td>
<td><input type="text" name="txtItems"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btnSubmit"></td>
</tr>
</tbody>

Use zebra form http://stefangabos.ro/php-libraries/zebra-form/
it is the best
will do both php and js validation

Use this check with jquery it might be help you
function formValidation()
{
if($("input[name='name']").trim() == "")
{
alert("Please enter the name");
$("input[name='name']").focus();
return false;
}
return true;
}

Try this...
function formValidation()
{
if($("input[name='name']").val().trim() == "")
{
alert("Please Enter The Name");
return false;
}
return true;
}

Related

php codeigniter don't update variable to mysql

I have a problem with my PHP project with CodeIgniter.
I have a form in which I pass variables to the Database and execute an UPDATE Query by modifying the data on the Database.
The problem is that when I insert the new data it does not give me error, it shows me the view in which it shows the data of the table but the data are not modified.
Can anyone help me understand please?
MODELS Hello_Model.php
function displayrecordsById($id)
{
$query=$this->db->query("SELECT * FROM Todolist WHERE id='".$id."'");
return $query->result();
}
function updaterecords($testo,$stato,$id)
{
$this->db->query("update Todolist SET testo='$testo',stato='$stato' WHERE id='".$id."'");
}
Views update_records.php
<html>
<head>
<title>Registration form</title>
</head>
<body>
<?php
//$i=1;
foreach($data as $row)
{
?>
<form method="post">
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr>
<td width="230">Id </td>
<td width="329"><input type="text" name="id" value="<?php echo $row->id; ?>"/></td>
</tr>
<tr>
<td>Testo </td>
<td><input type="text" name="testo" value="<?php echo $row->testo; ?>"/></td>
</tr>
<tr>
<td>Stato</td>
<td><input type='text' name='stato' value= "<?php echo $row->stato; ?> "/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="update" value="Update Records"/></td>
</tr>
</table>
</form>
<?php } ?>
</body>
</html>
</html>
Controllers Hello.php
public function updatedata()
{
$id=$this->input->get('id');
$result['data']=$this->Hello_Model->displayrecordsById($id);
$this->load->view('update_records',$result);
if($this->input->post('update'))
{
$n=$this->input->post('testo');
$e=$this->input->post('stato');
$this->Hello_Model->updaterecords($id,$n,$e);
redirect("http://simone.fabriziolerose.it/index.php/Hello/dispdata");
echo "Success!";
}
}
I took the code from this tutorial
i think problem in calling model function check:
change this:
$this->Hello_Model->updaterecords($id,$n,$e);
To
$this->Hello_Model->updaterecords($n,$e,$id);
and you change your custom query to CI query like:
For Update
$this->db->where("id",$id);
$this->db->update("Todolist",array("testo"=>$testo,"stato"=>$stato));
For Select:
$this->db->where("id",$id);
$query=$this->db->get("Todolist");
$row=$query->row();

javascript is not working, form is not validating

my login form is not getting validate. javascript is not working. please help me out. I am not getting any alerts.Do Tell me what is wrong with script.
<script type="text/javascript">
function checkForm(form)
{
if(form.username.value == "") {
alert("Error: Username cannot be blank!");
form.username.focus();
return false;
}
re = /^\w+$/;
if(!re.test(form.username.value)) {
alert("Error: Username must contain only letters, numbers and underscores!");
form.username.focus();
return false;
}
if(form.npassword.value == "") {
alert("Error: Username cannot be blank!");
form.npassword.focus();
return false;
}
re = /[A-Z]/;
if(!re.test(form.npassword.value)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
form.npassword.focus();
return false;
}
alert("You entered a valid password: " + form.npassword.value);
return true;
}
</script>
this is login form
<div class="section section_with_padding" id="contact">
<h2>Change Password</h2>
<div class="half left">
<h4> </h4>
<table width="91%" align='center' cellpadding= "0" cellspacing= "0" class='main_tab'>
<tr>
<td class='login_table' align='left'><form action="changepass.php" method="post" onsubmit="return checkForm(this);>
<table class="login_tab">
<td class='login_table' align='left'><form method='post'>
<tr>
<td colspan="2" class='login_nam' valign='middle'>Change Password</td>
</tr>
<tr>
<td class='login style1'>Username:</td>
<td class='login'><input type='text' name='username'> </td>
</tr>
<tr>
<td class='login style1'>Old Password:</td>
<td class='login'><input type='password' name='opassword'> </td>
</tr>
<tr>
<td class='login style1'>New Password:</td>
<td class='login'><input type='password' name='npassword'> </td>
</tr>
<tr>
<td class='login' colspan='2'><input type='submit' name='submit' value='Change'>
</td>
</tr>
</table>
</form> </td>
</tr>
</table>
</div>
</div>
please some one help in validating the login page with errors on not providing any input(it should display respective error message).
Looks like you have created a nested form. Please delete the second one.
<form action="changepass.php" method="post" onsubmit="return checkForm(this);> /* Form HTML */
<td class='login_table' align='left'>
<form method='post'> /* Remove this */
Hope this helps.
Peace! xD

HTML/PHP scripting - redirect to a new webpage after validation

I am using something similar to the following code to log a user in and redirect that user to a new web page once they are logged in:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>application</title>
</head>
<body bgcolor="#FFFFCC">
<div id="LoginPage">
<form method="GET" action="validateLogin.php">
<table style="font-size: 12px; line-height: 0;">
<tr>
<td align="right" bgcolor="#3333FF"><p id="text">Trader Id:</p></td>
<td align="left" bgcolor="#3333FF">
<input type="text" name="user">
</td>
</tr>
<tr>
<td align="right" bgcolor="#3333FF"><p id="text">Password:</p></td>
<td align="left" bgcolor="#3333FF"><input type="password" name="pass"></td>
</tr>
<tr>
<td>
<input type="hidden" size="50" value="<?php echo $var; ?>"/>
</td>
</tr>
<tr>
<td align="right" bgcolor="#FFFFCC"><p id="text"></p></td>
<td align="right" bgcolor="#FFFFCC"><p id="text"></p></td>
</tr>
<tr>
<td align="right" bgcolor="#FFFFCC"><p id="text"></p></td>
<td align="center" bgcolor="#B3B3B3"><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
EDITED
PHP
$query = mysql_query("SELECT username FROM Users WHERE username=$username");
if (mysql_num_rows($query) != 0) {
echo 1;
} else {
echo -1;
}
My PHP validation script (validateLogin.php) returns 1 if the user is logged in and -1 if they do not have an account. How can I modify this script so that when the user logs in, and logs in successfully, they are redirected to a new page rather than being shown the -1 or 1 return?
$query = mysql_query("SELECT username FROM Users WHERE username=$username");
if (mysql_num_rows($query) == 1){
header('Location:success.php'); //Login successfull
}else{
header('Location:login.php'); //Login failed
}
if( $var > 0 ) header('Location:success.php');
Just add this into your condition
if (mysql_num_rows($query) != 0) {
header('Location:success.php');
} else {
header('Location:login.php');
}

Dynamically enable and disable DIV via MySQL

Last night I was trying to figure out how I can how I can dynamically enable and disable span#txtCaptchaDiv on my contact form at the very bottom, above the submit button.
So I added a new field to MySQL, called captcha where I wanted to 1 to show and 0 to hide
So if I add 1 to field captcha the following code will show on my form.php
<label for="code">Write code below > <span id="txtCaptchaDiv" style="color:#F00"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label><!-- this is where the script will place a copy of the code for validation: this is a hidden field -->
<input type="text" name="txtInput" id="txtInput" size="30" />
If I add 0 to field captcha the captcha area will be blank on my form.php.
Can you guy help me out please?
here is my index.php code I currently have:
<?php
require_once("/config/database.php");
$con = mysql_connect($config["db_server"],$config["db_user"],$config["db_pass"]);
?>
<!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>Email FORM</title>
</head>
<body>
<div style="width: 550px; text-align: center;">
<span style="filter:alpha(opacity=60); opacity:.6; padding-left: 10px;"><br />
<?php
$data = mysql_query("SELECT * FROM formrelated")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
Print " ".$info['welcomemsg'] . "";
?>
</span></div>
<form id="form1" name="form1" method="post" action="submit.php" onsubmit="return checkform(this);">
<table width="454" border="1" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="123">Name</td>
<td width="325">
<input name="name" type="text" />
</td>
</tr>
<tr>
<td height="21">Address</td>
<td><input name="adress" type="text" /></td>
</tr>
<tr>
<td height="21"> </td>
<td><input name="address2" type="text" /></td>
</tr>
<tr>
<td height="21">Email</td>
<td><input name="email" type="text" /></td>
</tr>
<tr>
<td height="21">Tel</td>
<td><input name="email" type="text" /></td>
</tr>
</table>
<!--- captcha code here--->
<center>
<table width="454" height="122" border="0" cellspacing="0" cellpadding="0" background="reCAPbg.png">
<tr>
<td height="73" colspan="2" align="center" valign="middle"><label for="code"><span id="txtCaptchaDiv" style="color:#333; font-size:18px;"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label></td>
<td width="136" rowspan="2"> </td>
</tr>
<tr>
<td width="145"> type the code here:</td>
<td width="173" height="47" align="center"><input type="text" name="txtInput" id="txtInput" size="20" /></td>
</tr>
</table>
</center>
<!--- captcha code ends here--->
<input name="Submit" type="button" value="submit" />
</form>
<script type="text/javascript">
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
</script>
<script type="text/javascript">
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</body>
</html>
This will work for you... enjoy!
<?PHP
$query = mysql_query("SELECT captcha FROM formrelated WHERE id = '1'");
while ($row = mysql_fetch_assoc($query)) {
$captchathis = $row['captcha'];
if ($captchathis == "1") {
echo "YOUR HTML CODE HERE";
}
else {
echo "BLANK";
}
}
?>
Try it like this
<?PHP
if($mysqlResult['captcha'] === 1)
{
echo $myHtml;
}
?>
Where $mysqlResult is an array with the result from the query, $mysqlResult['captcha']is the value of the row captcha from your query and $myHtml is that HTML code you just showed on your answer.
Good luck! ;)
Reffer to
http://php.net/manual/en/
EDIT:
http://www.php.net/manual/en/language.types.array.php ( Array type on the manual )
http://www.php.net/manual/en/control-structures.if.php ( If control structure on the manual )
http://www.php.net/manual/en/ref.mysql.php ( MySQL native functions. deprecated. Preffer MySQLi )
http://www.php.net/manual/en/book.mysqli.php ( MySQLi extension )
http://www.php.net/manual/en/book.pdo.php ( PDO native php class )
Another answer to explain the basic construct of IF logic.
Suppose i have some condition i want to meet to do something; in this case, the following logic
SHOW my form with the basic inputs
IF condition 'captcha = 1' is met, SHOW input2 (captcha)
SHOW rest of the HTML
it would be like this in PHP
<?PHP
echo $myFormWithBasicInputs;
if($captcha === 1)
{
echo $input2;
}
echo $restOfHTML;
?>
In your case, $myFormWithBasicInput and $restOfHTML is already outputed as HTML. All you want to do is inject an PHP code in it to check if some condition is matched. It will be like this
<html>
<!-- MY FORM WITH BASIC INPUTS -->
<?PHP
$captcha = $mySQLresult['captchaRow'];
if($captcha === 1)
{
?>
<!-- CAPTCHA INPUT HERE -->
<?PHP
}
?>
<!-- REST OF HTML -->
</html>
be aware that this is an workaround with example code.
<?PHP
$mysql_query = "SELECT captcha FROM formrelated";
$captcha = $mySQLresult['captchaRow'];
if($captcha === 1)
{
?>
<!--- CODE---->
<table width="454" height="122" border="0" cellspacing="0" cellpadding="0" background="reCAPbg.png">
<tr>
<td height="73" colspan="2" align="center" valign="middle"><label for="code"><span id="txtCaptchaDiv" style="color:#333; font-size:18px;"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label></td>
<td width="136" rowspan="2"> </td>
</tr>
<tr>
<td width="145"> type the code here:</td>
<td width="173" height="47" align="center"><input type="text" name="txtInput" id="txtInput" size="20" /></td>
</tr>
</table>
<?PHP
}
?>
<!-- REST OF HTML -->

Javascript add MySQL data when checkbox is ticked

I am currently using this javscript and PHP code
<script>
function add(total)
{
form2.thetotal.value = document.forms["form1" + total].total.value;
}
</script>
<form name="form2">
<table width="800" border="0" cellspacing="0" cellpadding="10" style="position:fixed; z-index:-999; background-color:#FFF;">
<tr bgcolor="#eeeeee">
<td> </td>
<td colspan="2" width="50%"><strong>Total: </strong><input type="text" name="thetotal" id="thetotal" size="20" value="0" /></td>
<td colspan="2" width="50%"><strong>VAT:</strong> </td>
</tr>
<tr bgcolor="#eeeeee">
<td width="5%"> </td>
<td width="20%"><strong>Invoice Number</strong></td>
<td width="35%"><strong>Company</strong></td>
<td width="20%"><strong>Date</strong></td>
<td width="20%"><strong>Total</strong></td>
</tr>
</table>
</form>
<form name="form1">
<table width="800" border="0" cellspacing="0" cellpadding="10">
<?php
$sql="SELECT * from billing_pdf_archive order by invoice_number ASC ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
$counter++;
$sql2="SELECT * from customer where sequence = '".$result["customer_sequence"]."' ";
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
$result2=mysql_fetch_array($rs2);
$sql3="SELECT * from reseller where sequence = '".$result["reseller_sequence"]."' ";
$rs3=mysql_query($sql3,$conn) or die(mysql_error());
$result3=mysql_fetch_array($rs3);
if($result["customer_sequence"] != '0')
{
$company = $result2["company"];
}
elseif($result["reseller_sequence"] != '0')
{
$company = '<strong>Reseller: </strong>'.$result3["company"];
}
$total = $result["total"];
echo '<tr>
<td width="5%"><input type="checkbox" name="check" id="check" onclick=\'add('.$total.');\' /></td>
<td width="20%">'.$result["invoice_number"].'</td>
<td width="35%">'.$company.'</td>
<td width="20%">'.$result["datetime"].'</td>
<td width="20%">£'.$result["total"].'</td>
</tr>';
}
?>
</table>
</form>
so as you can see it is selecting from the MySQL database and i am trying to make it so when one of the checkboxes is ticked it adds the total into the "thetotal" text field (in form 2) but it is just leaving that box as zero - any ideas on what i could do?
You did not specify the total field for form 1, then it raised javascript error, it wont work.
Check it out
<script>
function add(total)
{
form2.thetotal.value = total + parseFloat(document.form1.formtotal.value);
}
</script>
<form name="form1">
<!-- replace field name formtotal with anything that you want-->
<!-- replace field value with anything that you get from your mysql result-->
<input type="text" name="formtotal" id="formtotal" value="10" />
</form>
Here is how you can do it (assuming total is int and not float):
<script>
function add(total, this_chk_bx)
{
//(if its float, use `parseFloat` instead of `parseInt`)
if(this_chk_bx.checked==true){
//add if its checked
var tot_1 = parseInt(form2.thetotal.value);
form2.thetotal.value = tot_1+parseInt(total);
}
else{
//subtract if its unchecked
}
}
</script>
.
in your php, you have to send the checkbox like this:
onclick=\'add('.$total.', this);\'
.

Categories