I have a form that allows me to edit data in my database. I need to
upload the image to a folder once the form is submitted. This is an edit page and I the way I have it set up is the image name is called from the database and the image is stored in the folder. Can anyone help me?
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<label> Job Name:</label><br><br>
<input type="text" name="job_name" value="<?php echo $name; ?>"/><br/>
<label></label><br><br>
<label>Job Thumbnail:</label><br><br>
<input id="upload" name="file" type="file" size="10"><br><br>
<input id="filename" type="text" name="job_timg" placeholder="This Fills Automatcially" value="<?php echo $timg; ?>"/><br/>
<label> Job Name:</label><br><br>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$name = mysql_real_escape_string(htmlspecialchars($_POST['job_name']));
$timg = mysql_real_escape_string(htmlspecialchars($_POST['job_timg']));
// check that name/image fields are both filled in
if ($name == '' || $timg == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $name, $timg, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE tbl_job SET job_name='$name', job_timg='$timg' WHERE job_id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: gallery_edit.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM tbl_job WHERE job_id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$name = $row['job_name'];
$timg = $row['job_timg'];
// show form
renderForm($id, $name, $timg, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
When dealing with files, the form must include a valid enctype.
<form action="" method="post" enctype="multipart/form-data">
For more information on dealing with files, visit the following page on PHP.net:
http://php.net/manual/en/reserved.variables.files.php
Related
I'm very new to PHP and I've cobbled this together from some other answers on here. Can anyone show me how to get the $errMsg to display? At present, a blank or incorrect name leads to a blank page. Is this because the form isn't being displayed again? If so, how should I go about 'reloading' the form with the error message?
<?php
$name = "Fred";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["name"])) {
if ($_POST["name"] == $name) {
include("welcomeFred.php");
}
else {
$errMsg = "Incorrect name";
}
}
else {
$errMsg = "Name required";
}
}
else { ?>
<html>
...
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" required>
<span><?php echo $errMsg;?></span>
<input type="submit" value="Submit">
</form>
...
</html>
<?php } ?>
You shouldn't put the rendering of the form in the else of your if structure. This is the reason your form isn't loaded when you submit the form.
Remove the else { ?> and <?php } ?> at the end of your file and it should work fine.
So i have managed to get rid of all the undefined errors and lined things up but when i go from my database page to my edit page so it posts the ID no data comes up and then even with posting to edit nothing happens in the database. I checked the php error log and mysql log and nothing there also tried some php debugging but got no data from there either, i am running out of ideas without some sort of error code to look at.
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
Status: Not working at all
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $date, $user, $model, $serial, $issue)
{
?>
<!DOCTYPE HTML>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
//if ($error != '')
//{
//echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
//}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>Date: *</strong> <input type="text" name="date" value="<?php echo $date; ?>"/><br/>
<strong>User: *</strong> <input type="text" name="user" value="<?php echo $user; ?>"/><br/>
<strong>Model: *</strong> <input type="text" name="model" value="<?php echo $model; ?>"/><br/>
<strong>Serial: *</strong> <input type="text" name="serial" value="<?php echo $serial; ?>"/><br/>
<strong>Issue: *</strong> <input type="text" name="issue" value="<?php echo $issue; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('conn.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = isset($_POST['id']) ? $_POST['id'] : '';
$date = isset($_POST['date']) ? $_POST['date'] : '';
$user = isset($_POST['user']) ? $_POST['user'] : '';
$model = isset($_POST['model']) ? $_POST['model'] : '';
$serial = isset($_POST['serial']) ? $_POST['serial'] : '';
$issue = isset($_POST['issue']) ? $_POST['issue'] : '';
// check that firstname/lastname fields are both filled in
if ($user == '' || $model == '' || $serial == '' || $issue == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $date, $user, $model, $serial, $issue);
}
else
{
// save the data to the database
mysql_query("UPDATE screen SET id='$id', date='$date', model='$model', serial='$serial', user='$user', issue='$issue'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: pview_screen.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM screen WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$id = isset($_GET['id']) ? $_GET['id'] : '';
$date = isset($_GET['date']) ? $_GET['date'] : '';
$user = isset($_GET['user']) ? $_GET['user'] : '';
$model = isset($_GET['model']) ? $_GET['model'] : '';
$serial = isset($_GET['serial']) ? $_GET['serial'] : '';
$issue = isset($_GET['issue']) ? $_GET['issue'] : '';
// show form
renderForm($id, $date, $model, $serial, $user, $issue);
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
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.
This is what I did in a nutshell:
<?php
// define variables and initialize with empty values
//error variables
$agentNameErr = "";
//non-error variables
$agentemail = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["agentname"])) {
$agentNameErr = "Missing";
}
else {
$agentname = $_POST["agentname"];
}
}
// form
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<input name="agentname" type="text" id="agentname" autocomplete="on" placeholder="Agent Name" value= "<?php echo htmlspecialchars($agentname);?>" />
//only shows up if $agentNameErr is assigned the value of "Missing"
<span class="error"><?php echo $agentNameErr;?></span>
</form>
It checks if $agentname is erroneous (blank). If it's not blank, I don't know how to proceed. I want it to just automatically submit all the information without any additional user input to a review page so the user can see if the name was spelled correctly. And then they can do a final submission.
I don't know MySQL.
In normal english:
//user presses the submit button
if ($agentname has error)
stay on page and display errors
else
submit automatically to next page (order review page for visual checking)
What do I do to "submit automatically to next page"?
Use a php session.
if ($agentname has error)
stay on page and display errors
else
{
$_SESSION['key1'] = 'something'
$_SESSION['key2'] = 'something else'
...
header('location: ' . $next_page);
}
If you don't know how to use php sessions see the examples here
Try this:
<?php
$agentNameErr = "";
$agentemail = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["agentname"])) {
$agentNameErr = "Missing";
} else {
$agentname = $_POST["agentname"];
header("Location: nextpage.php?agent=".$agentname);
}
} else {
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<input name="agentname" type="text" id="agentname" autocomplete="on" placeholder="Agent Name" value= "<?php echo htmlspecialchars($agentname);?>" />
//only shows up if $agentNameErr is assigned the value of "Missing"
<?php if(!empty($agentNameErr)) { ?>
<span class="error"><?php echo $agentNameErr;?></span>
<?php } ?>
</form>
<?php } ?>
Keep it simple. Capture the entire contents of the form and store in a session variable.
$agentNameErr = '';
$agentemail = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['agentname'])) {
$agentNameErr = 'Missing';
} else {
$_SESSION['agent-form'] = $_POST;
// Move to next page
header('Location: nextpage.php');
exit;
}
}
Once forwarded to the next page you can access the form data from the session variable.
// Entire contents of form
print_r($_SESSION['agent-form']);
// "agentname" data
print_r($_SESSION['agent-form']['agentname']);
I have a form that a user can enter in first name, last name and email. You can submit this form multiple times in case you would like to send to more users by simply clicking on submit (of course, so long as the fields are entered correctly using sanitation and validation).
if (isset($_POST['Submit'])) {
//sanitize if field (like email) is not empty, then validate it using a function
// such as FILTER_VALIDATE_EMAIL and FILTER_SANITIZE_STRING
//like if ($_POST['email'] != "") { do the sanitation and validation here }
//then if no error send the email
//then $_POST = array(); to clear up form for the next entry
}
<form> form here</form>
Do you guys have an idea by just laying out this concept? Or do you need a sample code? Thanks for your help.
Was trying to use what Joe suggested but didn't work. Any further help?
session_start();
if (isset($_POST['Submit'])) {
if (isset($_SESSION['submission_count'])) {
if ($_SESSION['submission_count'] > 10) {
echo "You can't submit so many!";
exit;
}
}
else {
$_SESSION['submission_count'] = 0;
}
$_SESSION['submission_count'] += 1;
// Form validation and sanitation
// Send email
}
?>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
First Name:
<input type="text" name="firstname" value="<?php echo $_POST['firstname']; ?>" size="50" /><br />
Last Name:
<input type="text" name="lastname" value="<?php echo $_POST['lastname']; ?>" size="50" /><br />
Email Address:
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="50"/> <br/><hr />
<br/>
<input type="submit" class="button" name="Submit" />
</form>
You can store a counter in $_SESSION.
http://www.php.net/manual/en/intro.session.php
<?php
// Starting the session
session_start();
if (isset($_POST['Submit'])) {
if (isset($_SESSION['submission_count'])) {
if ($_SESSION['submission_count'] > 5) {
echo "You can't submit so many!";
exit;
}
}
else {
$_SESSION['submission_count'] = 0;
}
$_SESSION['submission_count'] += 1;
// Do the rest of your form submission
}