PHP form not validating with functions - php

<!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>

Related

Return the entered data in a form if the error array is empty

i have this code
first file is a form that gets data and perform some basic email validation
second file gets all data and performs php validation and returns error messages that are stored in an array if the user inputs something wrong.
my question is that how can i display the contents of the form if there is no errors and the error array is empty.
<?php
$error = $_GET['message'];
?>
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validateEmail()
{
var email = document.getElementById('email').value;
var reEmail = document.getElementById('reEmail').value;
atpos = email.indexOf("#");
dotpos = email.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email")
document.getElementById('email').focus() ;
return false;
}
if (email === reEmail){
return true;
}
alert("emails don't match!");
return false;
}
</script>
</head>
<body>
<div>
<?php
if ($error == ""){
}
else{
foreach ($error as $key => $value) {
echo "<h1>". $value . "</h1>";
}
}
?>
</div>
<form action="registerExec.php" method="post" name="myForm" onsubmit="return(validateEmail());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td align="right">Email</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td align="right">Retype Email</td>
<td><input type="text" name="reEmail" id="reEmail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
second file:
<?php
$email = $_POST['email'];
$zip = $_POST['zip'];
$name = $_POST['name'];
$message = array(" ");
$goodjob = 'goodjob';
if ($email == "" || $zip == "" || $name ==""){
array_push($message, "Email, Zip, Name should not be empty!");
// chedk if any of these fields is empty
}
if ($name != ""){
if (is_numeric($name)) {
array_push($message, "don't include numberss in name");
}
}
if (is_numeric ($zip) ){
} else {
array_push($message, "zip is not a number!");
}
if (strlen($zip) != 5){
array_push($message, "Wrong Zip!");
}
$finalmessage = http_build_query(array('message' => $message));
header("Location: http://localhost/register/classexercise.php?".$finalmessage);
?>
Here, try this, let me know if you are expecting something else.
<?php
$error = $_GET['message'];
?>
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validateEmail(){
var email = document.getElementById('email').value;
var reEmail = document.getElementById('reEmail').value;
atpos = email.indexOf("#");
dotpos = email.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email")
document.getElementById('email').focus() ;
return false;
}
if (email === reEmail){
return true;
}
alert("emails don't match!");
return false;
}
</script>
</head>
<body>
<div>
<?php
if ($error == ""){
}
else{
foreach ($error as $key => $value) {
echo "<h1>". $value . "</h1>";
}
}
?>
</div>
<form action="registerExec.php" method="post" name="myForm" onsubmit="return(validateEmail());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td align="right">Email</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td align="right">Retype Email</td>
<td><input type="text" name="reEmail" id="reEmail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Your PHP to display the form content -
<?php
$email = $_POST['email'];
$zip = $_POST['zip'];
$name = $_POST['name'];
$country = $_REQUEST['country'];
$message = array();
$goodjob = 'goodjob';
if ($email == "" || $zip == "" || $name ==""){
array_push($message, "Email, Zip, Name should not be empty!");
// chedk if any of these fields is empty
}
if ($name != ""){
if (is_numeric($name)) {
array_push($message, "don't include numberss in name");
}
}
if (!is_numeric ($zip)){
array_push($message, "zip is not a number!");
}
if (strlen($zip) != 5){
array_push($message, "Wrong Zip!");
}
if (empty($message)){
array_push($message, $name);
array_push($message, $email);
array_push($message, $zip);
$finalmessage = http_build_query(array('message' => $message));
header("Location: index.php?".$finalmessage);
} else {
$finalmessage = http_build_query(array('message' => $message));
header("Location: index.php?".$finalmessage);
}
?>

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>

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>

Using PHP functions to validate a form

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())

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