When i submit my form i just hit my first validation error. No data ever posts.
I'm new to all this stackOverflow stuff and new to all the database scene. To get what I've got i used some TUT's and Books.
Hope someone can help me.
$itemid = $_GET['page_id'];
$itemid = mysql_real_escape_string($itemid);
//get data from database that needs editing
$sql = mysql_query("SELECT * FROM content WHERE `page_id`='{$itemid}'")or die(mysql_error());
//if(!$sql) die ("Database access failed" . mysql_error());
if(isset($_POST['submit'])){
//start validation
//check fields are not empty
if(empty($pagetitle)) {
$error['page_title'] = 'enter a title.';
}
$pagecontent = trim($_POST['page_content']);
if(empty($pagecontent)){
$error['page_content'] = 'Please enter your content.';
}
//If validation is ok... cary on.. do this
if (!$error) {
$pageid = $_POST['page_id'];
$pagetitle = $_POST['page_title'];
$pagecontent = $_POST['page_content'];
//Update items
$sql = "UPDATE content SET page_title ='$pagetitle', page_content ='$pagecontent' WHERE page_id='$itemid'";
$resultupdate = mysql_query($sql)or die (mysql_error());
//Success Message
echo "Your site is now updated";
}//close if !error
}//close if form submit
//input validation checks input not empty
if (isset($error['page_title'])) {
echo "<p><span class=\"warning\">" . $error['page_title']."</span><p> ";
}
if (isset($error['page_content'])) {
echo "<p><span class=\"warning\">" . $error['page_content']."</span><p> ";
}
?>
<div>
<?php while ($row = mysql_fetch_object($sql)) { ?>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<input type="hidden" name="page_id" value="<?php echo $row->page_id; ?>" />
<div class="edit-title">
<h2><label>Page Title</label></h2>
<p><textarea name="page_title"><?php echo $row->page_title; ?></textarea></p>
</div><!-- end edit title -->
<div class="edit-content">
<h2><label>Page Content</label></h2>
<p><textarea name="page_content"><?php echo $row->page_content; ?></textarea></p>
</div><!-- end edit content -->
<div class="submit-form">
<input type="submit" name="submit" value="Update" />
</div>
</form>
<?php } ?>
</div>
You check if $pagetitle exists but you don't initialize it, you should have put :
if(empty($_POST['page_title'])) { ... }
EDIT :
if(isset($_POST['submit'])){
//start validation
//check fields are not empty
if(empty($_POST['page_title'])) {
$error['page_title'] = 'enter a title.';
}
$pagecontent = trim($_POST['page_content']);
if(empty($pagecontent)){
$error['page_content'] = 'Please enter your content.';
}
//If validation is ok... cary on.. do this
if (!$error) {
$pageid = $_POST['page_id'];
$pagetitle = $_POST['page_title'];
$pagecontent = $_POST['page_content'];
//Update items
$sql = "UPDATE content SET page_title ='$pagetitle', page_content ='$pagecontent' WHERE page_id='$itemid'";
$resultupdate = mysql_query($sql)or die (mysql_error());
//Success Message
echo "Your site is now updated";
}//close if !error
}//close if form submit
Related
I am writing a form to create a login username and password.
If the account creation is successful, I would like the user to then be taken to the actual LOGIN form.
I have created a series of checks with the variable $errcheck being passed so the program knows what to do. If there is an error, $errcheck will be set to 1. Its default is 0.
If there are errors in the input fields, the account creation form will be displayed again and if everything is fine then it will INSERT user details into the table and take the user to the LOGIN page.
However, I can only get the page to reload itself each time after the info is added to the table. Is what I'm doing with the action part of the form even allowed? I went ahead and included all of my code in case there were any questions about it. Thank you.
<!DOCTYPE html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$busow_namef = $busow_namel= $owner_email = $bus_psswd = $psswd_confirm = "";
$busname_ERR = $busowname_ERR = $owneremail_ERR = $psswd_ERR =
$psswdconfirm_ERR = "";
$errcheck = 0;
if ($_SERVER["REQUEST_METHOD"]=="POST") {
//??????????????????? Check Login information ???????????????????
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($_POST["busow_namef"])) {
$busowname_ERR = "Business owner's name is required";
$errcheck = 1;
} else {
$busownamef = test_input($_POST["busow_namef"]);
}
if (empty($_POST["busow_namel"])) {
$busowname_ERR = "business owner's name is required";
$errcheck = 1;
} else {
$busownamel = test_input($_POST["busow_namel"]);
}
if (empty($_POST["bus_psswd"])) {
$psswd_ERR = "You must enter a password.";
$errcheck = 1;
} else if ((mb_strlen($_POST["bus_psswd"])) < 8) {
$psswd_ERR = "The password must be 8-10 characters long and only include numbers and letters.";
$errcheck = 1;
} else {
$bus_psswd = test_input($_POST["bus_psswd"]);
}
if (empty($_POST["psswd_confirm"])) {
$psswdconfirm_ERR = "Please confirm password.";
$errcheck= 1;
} else if ($_POST["psswd_confirm"] != $_POST["bus_psswd"]) {
$psswdconfirm_ERR = "The passwords do not match.";
$errcheck = 1;
} else {
$psswd = test_input($_POST["psswd_confirm"]);
$h_psswd = password_hash($psswd, PASSWORD_DEFAULT);
}
if (empty($_POST["tandc"])) {
$checktandc_ERR= "You must accept the terms and conditions.";
$errcheck= 1;
} else {
$tandc = test_input($_POST["tandc"]);
}
if (empty($_POST["owner_email"])) {
$owneremail_ERR = "Please enter an email address.";
$errcheck = 1;
} else {
$_POST["owner_email"] = (filter_var($_POST["owner_email"], FILTER_SANITIZE_EMAIL));
}
if (filter_var($_POST["owner_email"] , FILTER_VALIDATE_EMAIL)){
$owneremail = $_POST["owner_email"];
} else {
$owneremail_ERR = "Please enter a valid email address.";
$errcheck = 1;
}
//???????????????? Connect to database ??????????????????????????
$link = mysqli_connect('domain', 'user', 'passwd');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db(database, $link);
if (!mysqli_select_db(louisville_ky1, $link)) {
echo "database not selected";
} else {
$sql = "SELECT owner_email FROM 3bus_owners WHERE owner_email = '$owneremail' ";
$result = mysql_query($sql, $link);
if (mysql_num_rows($result) > 0 ) {
$errcheck = 1;
$owneremail_ERR = "This email is already registered. Please register with another address or click login.";
} else {
$errcheck = 0;
$query = "INSERT INTO 3bus_owners (owner_email, h_psswd, busow_namef, busow_namel) VALUES ('$owneremail', '$h_psswd', '$busownamef',
'$busownamel')";
$result2 = mysql_query($query, $link);
} //end if num rows >0
}//end connection check
} // ???????????????????? end if server request method ????????????????
?>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~Begin HTML FORM~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<h2>Create Business Login</h2>
<br>
<form method="post" action="<?php if ($errcheck = 1) { echo
htmlspecialchars($_SERVER["PHP_SELF"]);
} else { echo 'ownersignin.php'; }?>">
Business Owner's Name:<br>
First Name:<br><input type="text" name="busow_namef" value="<?php echo
$busow_namef;?>">
<span class="error">* <?php echo $busowname_ERR;?></span>
<br>
Last Name:<br><input type="text" name="busow_namel"value="<?php echo
$busow_namel;?>">
<span class="error">* <?php echo $busowname_ERR;?></span>
<br>
Business Owner's E-mail: *this will be your username for login and does not have to be posted in listing
<br>
<input type="text" name="owner_email" size="40"value="<?php echo
$owner_email;?>">
<span class="error">*<?php echo $owneremail_ERR;?></span>
<br><br>
Password: <input type="password" name="bus_psswd" size="11" maxlength="10">
<span class="error">*<?php echo $psswd_ERR;?></span>
<br>
Confirm Password: <input type="password" name="psswd_confirm" size="11" maxlength="10">
<span class="error">*<?php echo $psswdconfirm_ERR;?></span>
<br>
<br>
<input type="checkbox" name="tandc">I have read and accept the
<a href="/termsandconditions.php" target= "_blank">Terms and
Conditions</a>.
<span class="error">*<?php echo $checktandc_ERR;?></span>
<br>
<br>
<input type="submit" name="submit" value="Create Login">
</form>
</body>
snippit from above:
<form method="post" action="<?php if ($errcheck = 1) { echo htmlspecialchars($_SERVER["PHP_SELF"]); } else { echo 'ownersignin.php'; }?>">
I have never seen a form action attribute written like this, but... try changing the "double quotes" around "PHP_SELF" to single quotes: $_SERVER['PHP_SELF']. That could be causing a problem because it might be getting interpreted as:
action="<?php if ($errcheck = 1) { echo htmlspecialchars($_SERVER["
Then, verify that this code sample didn't come from the page: "ownersignin.php". It just sounds like that would be the name of this page instead of the name of the page the form would redirect to.
echo 'ownersignin.php';
If this is the name of the page your code is in, it would send you in an infinite loop.
You shouldn't reprint the registration form when the registration is successful. Instead, redirect the user to the signin form.
After all the validation checks, do:
if (!$errcheck) {
header("Location: ownersignup.php");
exit;
}
?>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~Begin HTML FORM~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<h2>Create Business Login</h2>
<br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
...
I have this form that I'm working with off a tutorial. I'm trying keep the fields populated when there is a validation error.
Here is my form:
<div class="add">
<?php $errors4 = errors_seesion_funtion(); ?>
<?php echo form_errors($errors4); ?>
<div class="error-message"><?php echo message(); ?></div>
<div class="done"><input name="Done" type="button" value="Done" /></div>
<h2>ADD New Department:</h2>
<form action="create-department-process.php" method="post">
<p class="department-name">Department name:
<input type="text" name="department_name" id="department-name" value="<?php if (isset($_POST['department_name'])) { echo htmlentities($_POST['department_name']); } ?>" />
<span class="error">* <?php if (!empty($errors4)) { echo "<div class=\"error\">";
echo "Hi";
echo "</div>";
}
?></span>
</p>
<p class="department-name">Test name:
<input type="text" name="test_name" id="test-name" value="" />
<span class="error">* <?php /*echo form_errors($errors4); */
if (!empty($errors4)) {
echo "<div class=\"error\">";
echo "test name";
echo "</div>";
}
?></span>
</p>
<input type="submit" name="dept_added" id="add-btn" value="ADD Department" />
</form>
<br />
<div class="cancel">Cancel</div>
Here is my Session:
session_start();
function message() {
if (isset($_SESSION["message"])) {
$output = "<div class='message'>";
$output .= htmlentities($_SESSION["message"]);
$output .= "</div>";
// clear message after use
$_SESSION["message"] = null;
return $output;
}
}
function errors_seesion_funtion() {
if (isset($_SESSION["errors3"])) {
$errors2 = $_SESSION["errors3"];
$_SESSION['post_data'] = $_POST;
// clear message after use
$_SESSION["errors3"] = null;
return $errors2;
}
}
Here is my Validation Functions:
$errors_array = array();
function fieldname_as_text($fieldname) {
$fieldname = str_replace("_", " ", $fieldname);
$fieldname = ucfirst($fieldname);
return $fieldname;
}
function has_presence($value) {
return isset($value) && $value !== "";
}
function validate_presences($required_fields) {
global $errors6;
foreach($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors6[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
Here is my create-department-process.php
if (isset($_POST['dept_added'])) {
$department_name = mysql_prep($_POST["department_name"]);
//Validations for form
$required_fields = array("department_name", "test_name");
validate_presences($required_fields);
if (!empty($errors6)) {
$_SESSION["errors3"] = $errors6;
redirect_to("add-department.php"); //this is the page the form is on
}
// Process the form
$query1 = "INSERT INTO departments (";
$query1 .= " department_name ";
$query1 .= ") VALUES ( ";
$query1 .= " '{$department_name}' ";
$query1 .= ") ";
$result1 = mysqli_query($db_connection, $query1);
if ($result1) {
// Success
$_SESSION["message"] = "Department created.";
redirect_to("add-department.php");
} else {
// Failure
$_SESSION["message"] = "Department creation failed.";
redirect_to("creation-error.php");
}
} else {
redirect_to("fail.php");
}
I've tried to put this in the value of my form
<?php if (isset($_POST['department_name'])) { echo htmlentities($_POST['department_name']); } ?>
But the value I type in doesn't stay when PHP runs the form validation and redirects. Does anyone have any idea on how I can keep the data I type into the form fields when I have a validation error?
Thank you for your time and Help! I really appreciate it!
I think your POST data is getting lost when you do this:
if (!empty($errors6)) {
$_SESSION["errors3"] = $errors6;
redirect_to("add-department.php"); //this is the page the form is on
}
I'm guessing redirect_to actually redirects your browser to the specified page, therefore resetting the REQUEST values and losing the pervious POST data. You either need to save the POST values in the session (a la errors_seesion_funtion) and access them from there in your form, or include the form above to preserve the original POST values.
The script is about editing data retrieved from database. It works fine (it edits the data) but the errors array is displayed immediately when the script runs. So i get all there errors: forgotten title, body, date.
For testing purposes i omit the title for example and click submit i get only the you forgot to enter your title
<?php
$page_title = 'Edit a Joke';
include ('includes/header.html');
echo '<h1>Edit a Joke</h1>';
// Check for a valid Joke ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_jokes.php
$id = $_GET['id'];
}
else { // No valid ID, kill the script.
echo '<p>This page has been accessed in error.</p>';
exit();
}
require ('mysqli_connect.php');
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$errors = array();
// Check for a title
if (empty($_GET['title'])) {
$errors[] = 'You forgot to enter title.';
} else {
$tit = mysqli_real_escape_string($dbc, ($_GET['title']));
}
// Check for body:
if (empty($_GET['body'])) {
$errors[] = 'You forgot to enter body.';
} else {
$bod = mysqli_real_escape_string($dbc, ($_GET['body']));
}
// Check for date:
if (empty($_GET['date'])) {
$errors[] = 'You forgot to enter date.';
} else {
$dat = mysqli_real_escape_string($dbc, ($_GET['date']));
}
if (empty($errors)) // If everything's OK.
{
// Make the query:
$q = "UPDATE joke SET title='$tit', body='$bod', date='$dat' WHERE joke_id=$id LIMIT 1";
$r = #mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// Print a message:
echo '<p>The joke has been edited.</p>';
} else { // If it did not run OK.
echo '<p class>The joke could not be edited. Sorry</p>'; // Public message.
}
}
else { // Report the errors.
echo '<p>The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p>';
}// End of if (empty($errors)) IF.
}// End of submit conditional.
// Always show the form...
// Retrieve the joke information:
$q = "SELECT title, body, date FROM joke WHERE joke_id=$id";
$r = #mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid joke ID, show the form.
// Get the joke's information:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Create the form:
echo '<form action="edit_joke.php" method="GET">
<p> Title: <input type="text" name="title" value="' . $row[0] . '" /></p>
<p> Body: <input type="text" style="height: 100" size="100" name="body" value="' . $row[1] . '" /> </p>
<p> Date: <input type="date" name="date" value="' . $row[2] . '" /> </p>
<p> <input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</form>';
} else { // Not a valid joke ID.
echo '<p>This page has been accessed in error.</p>';
}
mysqli_close($dbc);
?>
Change at the beginning:
if (isset($_GET['test'])) {
$errors = array();
// Check for a title
....
}
// Always show the form...
And add in your <form:
<input type="hidden" name="test" value="1">
well im working on a small html form.
<form class="contact" action="" method="POST">
<label>Name : </label><input type="text" name="name" value="<? echo $name; ?>"/>
<p class="middle"><label>Comment : </label><textarea name="message"></textarea><? echo $message; ?></p>
<label class="captcha"><img src="captcha.php" style="line-height: 30px;"></label><input type="text" name="code"/>
<input type="submit" class="csubmit" value="Now !" name="get"/>
</form>
and this is the php code:
<?php
if (isset($_POST['get'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "no name. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "no message <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "wrong captcha <br />";
}
if (!empty($error)) {
echo '<p class="error">Error :<br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
if (empty($error)) {
$message = mysql_real_escape_string($message);
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($_GET['id']);
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO comments(id, name, comment, time,approved)VALUES('$id', '$name', '$message', '$date', '0')");
echo "thank you";
}
}
?>
As you can see i user $message and $name to keep informations after a submit with wrong captcha code, but the problem is that i want to clear those fields after a submit with correct informations. Can you please tell me how can i clear form fields after a succesfull submit ?
You can use .reset() on your form.
$("#form")[0].reset();
You could follow that with Javascript too
document.getElementById('form').reset();
Or, if successful, redirect the user back to your contact page:
header("Location: contact.php"); // redirect back to your contact form
exit;
EDIT
<input type="submit" class="csubmit" value="Now !" name="get" onClick="clearform();" />
function clearform()
{
document.getElementById("name").value=""; //don't forget to set the textbox ID
document.getElementById("message").value=""; //don't forget to set the textbox ID
document.getElementById("code").value=""; //don't forget to set the textbox ID
}
Also use:
required="required"
so people will be required to fill out the input fields :)
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.
I keep getting a server error and I have limited it down to this code block. I must not be familiar with syntax. Can someone point out why I am getting a server error?? I posted all the code. HERE IT IS.....
<?php
// this starts the session
session_start();
$id = $_SESSION['userid'];
//this connects to the database
$con = mysql_connect("example","example","example");
mysql_select_db("example", $con);
//this is the info the user entered stored as variables
$leaguename = $_POST["leaguename"];
$members = $_POST["members"];
$leaguepassword = $_POST["leaguepassword"];
//this filters throught the variables to check against mysql injections
$leaguename = (filter_var($leaguename, FILTER_SANITIZE_STRING));
$leaguename = (filter_var($leaguename, FILTER_SANITIZE_URL));
$members = (filter_var($members, FILTER_SANITIZE_STRING));
$members = (filter_var($members, FILTER_SANITIZE_URL));
$leaguepassword = (filter_var($leaguepassword, FILTER_SANITIZE_STRING));
$leaguepassword = (filter_var($leaguepassword, FILTER_SANITIZE_URL));
//this is the variables that displays errors
$errors = "";
$result = mysql_query("SELECT * FROM League_Info WHERE League = '$leaguename'");
$result2 = mysql_fetch_array($result);
$result3 = $result2['League'];
$result4 = mysql_query("SELECT * FROM League_Info WHERE User_ID = '$id'");
$result5 = mysql_fetch_array($result4);
$result6 = $result5['User_ID'];
if ($id == "") {
$errors .= "<li>You must register or login to create a league!"; break;
} elseif ($result3 != "") {
$errors .= "<li>League Name already in use!"; break;
} elseif ($result6 != "") {
$errors .= "<li>You already have a league!"; break;
} else {
}
// no errors
if ($errors == "") {
$sql="INSERT INTO League_Info (League, User_ID, Commissioner, Year, Members, League_Password)
VALUES('$leaguename', '$id', 'y', '2012', '$members', '$leaguepassword')";
mysql_query($sql);
/* Redirect browser */
header("Location: http://www.yourfantasyfootballreality.com/invite.php");
/* Make sure that code below does not get executed when we redirect. */
exit;
} else {
}
?>
<html><head><title>Create a League</title></head>
<body>
<center><h1>Create a League</h1></center>
<center>
<div class="form" style= "width:500px; height:200px; background-color:gray; ">
<form action="createleaguevalidation.php" method="POST">
League Name: <input style="margin-left:0px;" type="text" name="leaguename" value="<?=$leaguename?>" /><br />
Number of Members: <input type="text" name="members" value="<?=$members?>"/><br>
League Password: <input type="password" name="leaguepassword" value="<?=$leaguepassword?>"><br>
<input type="submit" value="Create League" name="action">
<input type="reset" value="Reset">
</form>
<div style="background-color:#ffcccc; height:80px; width:500px;">
<?=$errors?>
</div>
</div>
<center>
</body>
</html>
If this code isn't inside a loop, then break is an error.
Your code is fine, just take out break;
To break the loop, put break; at the end of all the if statements.