Using PHP functions to validate a form - php

The following code worked perfectly before I put them into functions but I cannot figure out how to get this form to work correctly using the functions I created. I know I need to pass variables and create some proper main logic but I really don't know where to go from here. The end product should look something like this form: guestbookonescript
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Guestbook</title>
<meta charset="ISO-8859-1">
</head>
<?php
function check(){
$userErr = $emailErr = $noteErr = "";
$user = $email = $note = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user"]))
$userErr = "Please fill out a name.";
else
$user = $_POST["user"];
if (empty($_POST["email"]))
$emailErr = "Please fill out an email.";
else
$email = $_POST["email"];
if (empty($_POST["note"]))
$noteErr = "Please give us your comments.";
else
$note= $_POST["note"];
}
}
function display(){
print<<<TABLE_BLOCK
<h2>Please Sign Our Guestbook</h2>
<form method="post" action="mock.php">
<table>
<tr>
<td>Name:</td><td><input type="text" size="34" name="user" value="" /><span class="error"><br> $userErr</span></td>
</tr>
<tr>
<td>Email: </td><td><input type="text" size="34" name="email" value="" /><span class="error"><br> $emailErr</span></td>
</tr>
<tr>
<td valign="top">Comments: </td><td><textarea rows="5" cols="25" name="note"> </textarea><span class="error"><br> $noteErr</span></td>
</tr>
<tr>
<td></td><td></td>
</tr>
<tr>
<td></td><td align="right"><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
TABLE_BLOCK;
}
function result(){
print<<<TABLE_BLOCK
<h2>Your Input:</h2>
<table>
<tr>
<td>Name:</td><td>$user</td>
</tr>
<tr>
<td>Email: </td><td>$email</td>
</tr>
<tr>
<td valgin="top">Comments: </td><td>$note</td>
</tr>
</table>
TABLE_BLOCK;
}
if(isset($_REQUEST['submit']))
check();
else
display();
result();
?>
</body>

What Alon is trying to say is that all of your variables are caught in the local scope, to avoid this, you need tell the offending variables that they belong in the global scope. Technically, you don't need to initialize them first, but it's good practice.
Note, you need to ensure that your variables are in the global scope in each function you're using them in.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Guestbook</title>
<meta charset="ISO-8859-1">
</head>
<?php
$userErr = $emailErr = $noteErr = "";
$user = $email = $note = "";
function check(){
global $user, $email, $note;
global $userErr, $emailErr, $noteErr;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user"]))
$userErr = "Please fill out a name.";
else
$user = $_POST["user"];
if (empty($_POST["email"]))
$emailErr = "Please fill out an email.";
else
$email = $_POST["email"];
if (empty($_POST["note"]))
$noteErr = "Please give us your comments.";
else
$note = $_POST["note"];
}
}
function display(){
global $userErr, $emailErr, $noteErr;
print<<<TABLE_BLOCK
<h2>Please Sign Our Guestbook</h2>
<form method="post" action="/">
<table>
<tr>
<td>Name:</td><td><input type="text" size="34" name="user" value="" /><span class="error"><br> $userErr</span></td>
</tr>
<tr>
<td>Email: </td><td><input type="text" size="34" name="email" value="" /><span class="error"><br> $emailErr</span></td>
</tr>
<tr>
<td valign="top">Comments: </td><td><textarea rows="5" cols="25" name="note"> </textarea><span class="error"><br> $noteErr</span></td>
</tr>
<tr>
<td></td><td></td>
</tr>
<tr>
<td></td><td align="right"><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
TABLE_BLOCK;
}
function result(){
global $user, $email, $note;
print<<<TABLE_BLOCK
<h2>Your Input:</h2>
<table>
<tr>
<td>Name:</td><td>$user</td>
</tr>
<tr>
<td>Email: </td><td>$email</td>
</tr>
<tr>
<td valgin="top">Comments: </td><td>$note</td>
</tr>
</table>
TABLE_BLOCK;
}
if(isset($_REQUEST['submit']))
check();
display();
result();
?>
</body>

You need to define variables that was declared outside the function as global. Put this line at start of your function, after function result(){
global $user,$email,$note;
note that variables declared inside the function scope will be deleted after the function execution. you need to declare $user,$email,$note ouside check() (and just declare them as global inside check())

Related

More than one row does not inserted into database..PHP and jQuery

I have created dynamic table from where I can insert data into database, But problem is that when I try to insert more than 1 row into database, its goes nowhere. As I have tried to insert only 1 row as its inserting successfully which advice me what I'm doing wrong
<?php
include "includes/config.php";
?>
<?php
$error_array = array();
$name = $email = $phone = $name_Error = $email_Error =$phone_Error ="";
if(isset($_POST['save_all']))
{
if($_POST['name'] !="")
{
$name = $_POST['name'];
}
else
{
$name_Error ="Enter name";
array_push($error_array,$name_Error);
}
if($_POST['email'] !="")
{
$email = $_POST['email'];
}
else
{
$email_Error ="Enter email";
array_push($error_array,$email_Error);
}
if($_POST['phone'] !="")
{
$phone = $_POST['phone'];
}
else
{
$phone_Error ="Enter phone";
array_push($error_array,$phone_Error);
}
if(count($error_array) == 0)
{
$insert_user = "INSERT INTO users(user_id,name,email,phone) values(NULL,'$name','$email','$phone')";
$res_users = mysqli_query($link,$insert_user);
if($res_users >0)
{
$success_Message = "record inserted";
array_push($error_array,$success_Message);
}
}
}
?>
<!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" />
<link rel="stylesheet" type="text/css" href="<?php echo CSS_URL;?>add_more.css">
<script src="<?php echo JS_URL;?>jquery.js"></script>
<title>Add More</title>
<script>
$(document).ready(function()
{
var count = 1;
$(".addmore_Button").click(function()
{
count++;
$(".addmore_Form_Table").append('<tr><td class="serial_num"><span>'+count+'</span></td><td><input type="text" name="name"/></td><td><input type="text" name="email"/></td><td><input type="text" name="phone"/></td><td><img id="delete'+count+'" style="margin-left:35px; margin-right:10px" onclick="deleteRow(this.id);" src="images/delete (1).png" /></tr>');
});
});
function deleteRow(id)
{
confirm("Are you sure you want to delete...?");
$("#"+id).parent().parent().parent().remove();
}
$(document).ready(function()
{
$("#delete_User").on('click',function()
{
alert("Sorry, you cant delete first row...!!");
});
});
</script>
</head>
<body>
<table class="addmore_Table">
<tr>
<th class="heading">Sr.No</th>
<th class="heading">Email</th>
<th class="heading">Name</th>
<th class="heading">Phone</th>
<td><input type="submit" class="addmore_Button" name="addmore_Button" value="Add More" /></td>
</tr>
</table>
<form name="addmore_Form" action="" method="post" class="addmore_Form">
<table class="addmore_Form_Table">
<tr>
<td></td>
<td><?php echo $name_Error;?></td>
<td><?php echo $email_Error;?></td>
<td><?php echo $phone_Error;?></td>
<td></td>
</tr>
<tr>
<td class="serial_num"><span>1</span></td>
<td><input type="text" name="name" value="<?php echo $name;?>" /></td>
<td><input type="text" name="email" value="<?php echo $email;?>" /></td>
<td><input type="text" name="phone" value="<?php echo $phone;?>" /></td>
<td><img id="delete_User" style="margin-left:35px; margin-right:10px" src="images/delete (1).png" /></td>
</tr>
</table>
<input type="submit" class="save_all" name="save_all" value="Save All" />
</form>
</body>
</html>

Registration redirecting even with validation errors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have created a php registration page. Everything is running well. It shows an error when I leave text box empty.
However when I use the action method to redirect the registration page, it's always redirecting, both when I am writing something and when I'm not entering something in the text box.
I want that the page doesn't redirect when the field is empty. I use a boolean and the break method, but nothing is happening.
Can anyone help me here on this issue?
<html>
<?php
include 'header.php';
$nameErr = $emailErr = $genderErr = $passwordErr = $addErr = $phoneErr = "";
$fullname = $email = $gender = $password = $address = $phone = "";
$flag = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fullname"])) {
$nameErr = "Name is required";
break;
$flag
}
else {
$fullname = test_input($_POST["fullname"]);
}
if (empty($_POST["password"])) {
$passwordErr = " password required";
break;
}
else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
break;
}
else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["address"])) {
$addErr = "Address required";
break;
}
else {
$gender = test_input($_POST["address"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
break;
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["phone"])) {
$phoneErr = "phone no required";
break;
} else {
$phone = test_input($_POST["phone"]);
}
}
?>
<body>
<br>
<div class="regis_div" >
<form name="myForm" <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="post" action="thanks.php" >
<table class="table2" border="0" align="center" cellspacing="15" >
<tr>
<td colspan="3"><h1><center>User Registration Form</center></h1></td>
</tr>
<tr>
<td width="291">       Full name:</td>
<td width="150"><input type="text" name="fullname"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $nameErr;?></span></font></td>
</tr>
<tr>
<td>      Password</td>
<td><input type="password" name="password"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $passwordErr;?></span></td>
</tr>
<tr>
<td>      Confirm Password</td>
<td><input type="password" name="Confirmpassword"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $passwordErr;?></span></td>
</tr>
<tr>
<td>      Email Address:</td>
<td><input type="text" name="email" ></td>
<td><span class="error"><font size="2" color="red">* <?php echo $emailErr;?></span></td>
</tr>
<tr>
<td>      Gender:</td>
<td><input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male</td>
<td><span class="error"><font size="2" color="red">* <?php echo $genderErr;?></span></td>
</tr>
<tr>
<td height="80">      Address:</td>
<td><textarea type="text" name="Address" class="address" rows="4" cols="20" ></textarea></td>
<td><span class="error"><font size="2" color="red">* <?php echo $addErr;?></span></td>
</tr>
<tr>
<td>      Phone No:</td>
<td><input type="text" name="phone"></td>
<td><span class="error"><font size="2" color="red">* <?php echo $phoneErr;?></span></td>
</tr>
<tr>
<td colspan="2"><input class="regbtn2" type="submit" value="Submit" align="center" ></td>
</tr>
</table>
</form>
</div>
</body>
</html>
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
break;
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["phone"])) {
$phoneErr = "phone no required";
break;
} else {
$phone = test_input($_POST["phone"]);
}
break will only break out of for, foreach, while, do-while and switch structures, not if statements.
It's also unclear exactly which script you believe should be handling your form submission:
<form name="myForm" <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="post" action="thanks.php" >
If the script you posted above is named form.php, then the above line will produce the following (invalid) markup:
<form name="myForm" form.php method="post" action="thanks.php" >
When submitted, execution will immediately flow to thanks.php and none of your PHP error checking (as posted above) will run. If you want the code you posted above to run, you should change that form tag to this:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
Then, once you're satisfied that your submission has no errors, you can redirect the user to a new page:
header('Location: thanks.php');
You should also note that, when that line is executed, you will loose access to all of your existing POST data, so you must do something with it if you wish to preserve it before redirecting with a header.
However, there's quite a few issues with your code.
if (empty($_POST["fullname"])) {
$nameErr = "Name is required";
break; // Already mentioned this line will have no effect
$flag // Why is this line here?
}
How will you know, using your current structure, if any error was encountered? It would have to look like this:
if(isset($nameErr) || isset($passwordErr) || isset($emailErr) || ...)
You can simplify that with an array:
if (empty($_POST["fullname"])) {
$errors['name'] = "Name is required";
// ...
}
// ...
if(count($errors)) {
// Some error occurred, don't redirect
} else {
// ... do something with POST data ...
header('Location: thanks.php');
exit; // Always exit or die after issuing a header redirect
}
And the associated markup:
<?php if(isset($errors['name'])) { ?>
<span class="error">
<font size="2" color="red">*
<?php echo $errors['name']; ?>
</font> <!-- Don't forget to close all of your opened HTML tags -->
</span>
<?php } ?>

PHP: Updating password from MD5

I have problem with update my password from MD5 I don't get any errors but they didn't update !
here's my code .. I saw the questions about MD5 in Stackoverflow. and adding more row but unfortunately I can't update my passwords. there's a lot problems I know but I can't find them
<?php
$_SESSION["sess_user"] = "24";
include "config.php";
mysql_select_db("user_registration",$con);
if(isset($_POST['submit']))
{
$cur_password=$_POST['currentPassword'];
if(count($_POST)>0) {
$result = mysql_query("SELECT * FROM users WHERE id ='" . $_SESSION["sess_user"] . "' AND passwords = '".MD5($cur_password)."'");
$row=mysql_fetch_array($result);
if($row['passwords'] == MD5($cur_password)) {
mysql_query("UPDATE users SET passwords ='" . md5($_POST["newPassword"]) . "' WHERE id ='" . $_SESSION["sess_user"] . "'");
$message = "Password Changed";
} else $message = "Current Password is not correct";
}
}
?>
<html>
<head>
<title>Change Password</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script>
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;
currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;
if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "not same";
output = false;
}
return output;
}
</script>
</head>
<body>
<form name="frmChange" method="post" action="" onSubmit="return validatePassword()">
<div style="width:500px;">
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<table border="0" cellpadding="10" cellspacing="0" width="500" align="center" class="tblSaveForm">
<tr class="tableheader">
<td colspan="2">Change Password</td>
</tr>
<tr>
<td width="40%"><label>Current Password</label></td>
<td width="60%"><input type="password" name="currentPassword" class="txtField"/><span id="currentPassword" class="required"></span></td>
</tr>
<tr>
<td><label>New Password</label></td>
<td><input type="password" name="newPassword" class="txtField"/><span id="newPassword" class="required"></span></td>
</tr>
<td><label>Confirm Password</label></td>
<td><input type="password" name="confirmPassword" class="txtField"/><span id="confirmPassword" class="required"></span></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Submit" class="btnSubmit"></td>
</tr>
</table>
</div>
</form>
</body></html>

PHP form not validating with functions

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Guestbook</title>
<meta charset="ISO-8859-1">
</head>
<?php
function check($user, $email, $note, $userErr, $emailErr, $noteErr){
$userErr = $emailErr = $noteErr = "";
$user = $email = $note = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user"]))
$userErr = "Please fill out a name.";
else
$user = $_POST["user"];
if (empty($_POST["email"]))
$emailErr = "Please fill out an email.";
else
$email = $_POST["email"];
if (empty($_POST["note"]))
$noteErr = "Please give us your comments.";
else
$note= $_POST["note"];
}
if ($userErr=="" or $emailErr=="" or $noteErr=="")
display($user, $email, $note, $userErr, $emailErr, $noteErr);
else
displayResult($user, $email, $note);
}
function display($user, $email, $note, $userErr, $emailErr, $noteErr){
print<<<TABLE_BLOCK
<h2>Please Sign Our Guestbook</h2>
<form method="post" action="mock.php">
<table>
<tr>
<td>Name:</td><td><input type="text" size="34" name="user" value="" /><span class="error"><br> $userErr</span></td>
</tr>
<tr>
<td>Email: </td><td><input type="text" size="34" name="email" value="" /><span class="error"><br> $emailErr</span></td>
</tr>
<tr>
<td valign="top">Comments: </td><td><textarea rows="5" cols="25" name="note"></textarea><span class="error"><br> $noteErr</span></td>
</tr>
<tr>
<td></td><td></td>
</tr>
<tr>
<td></td><td align="right"><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
TABLE_BLOCK;
}
function displayResult($user, $email, $note){
print<<<TABLE_BLOCK
<h2>Your Input:</h2>
<table>
<tr>
<td>Name:</td><td>$user</td>
</tr>
<tr>
<td>Email: </td><td>$email</td>
</tr>
<tr>
<td valgin="top">Comments: </td><td>$note</td>
</tr>
</table>
TABLE_BLOCK;
}
if(isset($_REQUEST['submit']))
check($user, $email, $note, $userErr, $emailErr, $noteErr);
else
display($user, $email, $note, $userErr, $emailErr, $noteErr);
?>
</body>
</html>
I already know the error resides in my functions and or the logic I have to execute them. But I'm really unsure where exactly to go from here. Everything worked very well before I implemented the functions. Granted, I am a novice to this. When the submit button is pressed no data is sent to the displayResult() page and my error messages don't pop up whenever the form is submitted completely blank. Here's my current page: http://awsymposium.com/mock.php and the end product should look and operate similar to this: http://professorgustin.com/dpr206/guestbook/guestbookonescript.php
I have updated a little bit your code. I also strongly recomand that you also use a javascript validation for your fields.
Here is the code:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Guestbook</title>
<meta charset="ISO-8859-1">
</head>
<?php
function check($user, $email, $note){
$userErr = $emailErr = $noteErr = "";
if ($user=="")
$userErr = "Please fill out a name.";
else if ($email=="")
$emailErr = "Please fill out an email.";
else if ($note=="")
$noteErr = "Please give us your comments.";
if (($userErr !="") || ($emailErr !="") || ($noteErr !=""))
display($user, $email, $note, $userErr, $emailErr, $noteErr);
if(($userErr =="") && ($emailErr =="") && ($noteErr ==""))
displayResult($user, $email, $note);
}
function display($user=null, $email=null, $note=null, $userErr=null, $emailErr=null, $noteErr=null){
print<<<TABLE_BLOCK
<h2>Please Sign Our Guestbook</h2>
<form method="POST" action="test321.php">
<table>
<tr>
<td>Name:</td><td><input type="text" size="34" name="user" value="$user" /><span class="error"><br> $userErr</span></td>
</tr>
<tr>
<td>Email: </td><td><input type="text" size="34" name="email" value="$email" /><span class="error"><br> $emailErr</span></td>
</tr>
<tr>
<td valign="top">Comments: </td><td><textarea rows="5" cols="25" name="note">$note</textarea><span class="error"><br> $noteErr</span></td>
</tr>
<tr>
<td></td><td></td>
</tr>
<tr>
<td></td><td align="right"><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
TABLE_BLOCK;
}
function displayResult($user, $email, $note){
print<<<TABLE_BLOCK
<h2>Your Input:</h2>
<table>
<tr>
<td>Name:</td><td>$user</td>
</tr>
<tr>
<td>Email: </td><td>$email</td>
</tr>
<tr>
<td valgin="top">Comments: </td><td>$note</td>
</tr>
</table>
TABLE_BLOCK;
}
if(isset($_REQUEST['submit']))
check($_POST['user'], $_POST['email'], $_POST['note']);
else
display();
?>
</body>
</html>

php email validation (filter_validate_email) Not Working

I know there are numerous questions about this however I just can not seem to pick the error with my coding. I know it is something simple but I can not see it.
I have to create a form which when it is submitted the data will be inputted into MySQL database however the data needs to be validated first. I have 2 issues with this, the first being my email validation is not working using: (filter_var($email, filter_validate_email))
The problem is that when I submit the form it returns true regardless of if the email is valid or not.
If I put (!filter_var($email, filter_validate_email)) it returns false regardless of the input.
The second problem is that when loading the page it initially adds a blank entry into the SQL database and it adds entries that aren’t valid. i.e. if I don’t enter a name when the form is submitted the validation runs and I get the error message “name is required” but it still creates an entry in the table with a blank name.
I am using PHP version 5.3.27
This is for my tafe course i am doing however they are on holidays at the moment so any help would be greatly appreciated.
Coding from file 1:
<body>
<?php
// define variables and set to empty values
$nameErr;
$Name = $Address = $Phone = $Mobile = $Email="example#example.com";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["Name"]))
{$nameErr = "Name is required"; }
else {$Name = test_input($_POST["Name"]);}
if (empty($_POST["Address"]))
{$Address = "";}
else
{$Address = test_input($_POST["Address"]);}
if (empty($_POST["Phone"]))
{$Phone = "";}
else
{$Phone = test_input($_POST["Phone"]);}
if (empty($_POST["Mobile"]))
{$Mobile = "";}
else
{$Mobile = test_input($_POST["Mobile"]);}
if(filter_var($Email, FILTER_VALIDATE_EMAIL)){
echo"Valid Email";
}
else{
echo "Not a Valid Email";
}
echo phpinfo();
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form name="addcontact" method="post" action= "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>", "add-contact.php">
<table border="1" cellpadding="2">
<caption> Add New Caption </caption>
<tr>
<td><label for="Name">Name</label></td>
<td><input type="text" name="Name" size="30" maxlenght="50" tabindex="1"/> <span class="error">*<?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td><label for="Address">Address</label></td>
<td><textarea name="Address" cols="45" rows="5" tabindex="2"></textarea></td>
</tr>
<tr>
<td><label for="Phone">Phone</label></td>
<td><input type="text" name="Phone" size="20" maxlenght="20" tabindex="3" /> </td>
</tr>
<tr>
<td><label for="Mobile">Mobile</label></td>
<td><input type="text" name="Mobile" size="20" maxlenght="20" tabindex="4" /> </td>
</tr>
<tr>
<td><label for="Email">Email</label></td>
<td><input type="text" name="Email" size="30" maxlenght="50" tabindex="5" /></td>
</tr>
<tr>
<td colspan"2" align="center"><input type="Submit" name="Submit" value="Submit" tabindex="6"/>
</td>
</tr>
</table>
</form>
<?php
include("add-contact.php");
?>
</body>
</html>`
And coding from file 2:
<body>
<?php
$Name = $_POST["Name"];
$Address = $_POST["Address"];
$Phone = $_POST["Phone"];
$Mobile = $_POST["Mobile"];
$Email = $_POST["Email"];
$dbc = mysql_connect("localhost:3306", "root", "webbm01");
if (!$dbc)
die ('Could not connect: ' .mysql_error());
$db_selected = mysql_select_db("tafe", $dbc );
if (!$db_selected)
die ('Could not connect: ' . mysql_error());
$qry
= "INSERT INTO contacts (Name, Address, Phone, Mobile, Email) VALUES ('" . addslashes($Name) . "', '" . addslashes($Address) . "', '" . addslashes($Phone) . "', '" . addslashes($Mobile). "', '" . addslashes($Email) . "')";
$rst = mysql_query($qry, $dbc);
if ($rst)
{
echo "<b><font color='green'>The contact has been added.</font></b>";
}
else
{
echo "<b><font color='red'>Error: ". mysql_error($dbc) . ". The contact could not be added.</font></b>";
}
mysql_free_result($rst);
?>
</body>
</html>
check this code for email validation etc :
<body> <?php
// define variables and set to empty values
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {$nameErr = "Name is required"; }else {$Name = htmlspecialchars($_POST["Name"]);}
if (empty($_POST["Address"])) {$Address = "";}else{$Address = htmlspecialchars($_POST["Address"]);}
if (empty($_POST["Phone"])) {$Phone = "";}else {$Phone = htmlspecialchars($_POST["Phone"]);}
if (empty($_POST["Mobile"])) {$Mobile = "";}else {$Mobile = htmlspecialchars($_POST["Mobile"]);}
if(filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL)){ echo"Valid Email"; }else{ echo "Not a Valid Email"; }
}
?>
<form name="addcontact" method="post" action= "<?php echo $_SERVER["PHP_SELF"];?>">
<table border="1" cellpadding="2"> <caption> Add New Caption </caption> <tr> <td><label for="Name">Name</label></td> <td><input type="text" name="Name" size="30" maxlenght="50" tabindex="1"/> <span class="error">*<?php echo $nameErr;?></span> </td> </tr>
<tr> <td><label for="Address">Address</label></td> <td><textarea name="Address" cols="45" rows="5" tabindex="2"></textarea></td> </tr>
<tr> <td><label for="Phone">Phone</label></td> <td><input type="text" name="Phone" size="20" maxlenght="20" tabindex="3" /> </td> </tr>
<tr> <td><label for="Mobile">Mobile</label></td> <td><input type="text" name="Mobile" size="20" maxlenght="20" tabindex="4" /> </td> </tr> <tr> <td><label for="Email">Email</label></td> <td><input type="text" name="Email" size="30" maxlenght="50" tabindex="5" /></td> </tr> <tr> <td colspan"2" align="center"><input type="Submit" name="Submit" value="Submit" tabindex="6"/> </td> </tr> </table> </form>
</body> </html>`
The validation should happen in the file:
'add-contact.php'
Since this is what the from action is calling on submit.
The initial validators are meaningless since the $_POST array is not initialized.
The reason for the empty SQL insert statement is because you decide to do:
include("add-contact.php");
In the first file and it is running without valid $_POST initialization on each load of the page.
Remove the line include("add-contact.php");
This will stop the blank insertion in the database.
Also remove the action
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
Just try action="add-contact.php".
Email validation is working fine for me.

Categories