i have made a register form that keeps all of the created users in the database. Now, i want to put button (link, whatever) next to each of the created user, and when i click on the button, new login form to be shown, after i fill all of the required fields and press on update button, the edited user to be shown in database. Any help? Thanks in advance.
Code:
register form:
<?php
$errors = [];
$missing = [];
?>
<html>
<head>
<meta charset="utf-8">
<title>Facebook login</title>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php if(isset($_POST['send']) && count($missing) == 0){
echo "Thank you for register on our site! You profile details are listed bellow:";
?>
<p>Your name: <?php echo $_POST['name']; ?></p>
<p>Lastname name: <?php echo $_POST['lastName']; ?></p>
<?php
}else{
?>
<h1>Registration</h1>
<form method="post" action="register_user.php">
<?php if ($errors || $missing) : ?>
<p class="warning"> Please fill all of the empty items
</p>
<?php endif; ?>
<p>
<label for="username">Username
<?php
if ($missing && in_array('username', $missing)) : ?>
<span class="warning"> Please enter your first name</span>
<?php endif; ?>
</label>
<input type="text" name="username" id="username">
</p>
<p>
<label for="password">Enter your password
<?php
if ($missing && in_array('password', $missing)) : ?>
<span class="warning"> Please enter your password</span>
<?php endif; ?>
</label>
<input type="password" name="password" id="password">
<p>
<label for="re-password">Re-Enter your password
<?php
if ($missing && in_array('re-password', $missing)) : ?>
<span class="warning"> Please re-enter your password</span>
<?php endif; ?>
</label>
<input type="re-password" name="re-password" id="re-password">
</p>
<p>
<label for="name">First Name
<?php
if ($missing && in_array('name', $missing)) : ?>
<span class="warning"> Please enter your first name</span>
<?php endif; ?>
</label>
<input type="text" name="name" id="firstName">
</p>
<p>
<label for="lastName">Last Name
<?php
if ($missing && in_array('lastName', $missing)) : ?>
<span class="warning"> Please enter your last name</span>
<?php endif; ?>
</label>
<input type="name" name="lastName" id="lastName">
</p>
<p>
<label for="email">Enter your email adress
<?php
if ($missing && in_array('email', $missing)) : ?>
<span class="warning"> Please enter your email adress</span>
<?php endif; ?>
</label>
<input type="email" name="email" id="email">
</p>
<h3>Birthday</h3>
<p>
<label for="Select Month"> Select Month
<?php
if ($missing && in_array('month', $missing)) : ?>
<span class="warning"> Please select month</span>
<?php endif; ?>
</label>
<select name="month" id="month" >
<option value="Month"> Month </option>
<option value="Jan"> January </option>
<option value="Feb"> February </option>
<option value="Mar"> March </option>
<option value="Apr"> April </option>
<option value="May"> May </option>
<option value="June"> June </option>
<option value="July"> July </option>
<option value="Aug"> August </option>
<option value="September"> September </option>
<option value="Oct"> October </option>
<option value="Nov"> November </option>
<option value="Dec"> December </option>
</select>
</p>
<p>
<label for="Select Day"> Select Day
<?php
if ($missing && in_array('day', $missing)) : ?>
<span class="warning"> Please select Day</span>
<?php endif; ?>
</label>
<select name="day" id="day" >
<option value="Day"> Day </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4 </option>
<option value="5"> 5 </option>
<option value="6"> 6 </option>
<option value="7"> 7 </option>
<option value="8"> 8 </option>
<option value="9"> 9 </option>
<option value="10"> 10 </option>
<option value="11"> 11 </option>
<option value="12"> 12 </option>
<option value="13"> 13 </option>
<option value="14"> 14 </option>
<option value="15"> 15 </option>
<option value="16"> 16 </option>
<option value="17"> 17 </option>
<option value="18"> 18 </option>
<option value="19"> 19 </option>
<option value="20"> 20 </option>
<option value="21"> 21 </option>
<option value="22"> 22 </option>
<option value="23"> 23 </option>
<option value="24"> 24 </option>
<option value="25"> 25 </option>
<option value="26"> 26 </option>
<option value="27"> 27 </option>
<option value="27"> 27 </option>
<option value="28"> 28 </option>
<option value="29"> 29 </option>
<option value="30"> 30 </option>
<option value="31"> 31 </option>
</select>
</p>
<p>
<label for="Select Year"> Select Year
<?php
if ($missing && in_array('year', $missing)) : ?>
<span class="warning"> Please select year</span>
<?php endif; ?>
</label>
<select name="year" id="year" >
<option value="Year"> Year </option>
<option value="1990"> 1990 </option>
<option value="1991"> 1991 </option>
<option value="1992"> 1992 </option>
<option value="1993"> 1993 </option>
<option value="1994"> 1994 </option>
<option value="1995"> 1995 </option>
</select>
</p>
<p>
<label for="Select gender"> Select gender
<?php
if ($missing && in_array('Select gender', $missing)) : ?>
<span class="warning"> Please select your gender</span>
<?php endif; ?>
</label>
<input type="radio" name="gender" id="malegender">
<label for="gender" > Male</label>
<input type="radio" name="gender" id="femalegender">
<label for="gender"> Female</label>
</p>
<input type="submit" name="send" id="send" value="send">
</form>
<?php } ?>
</body>
</html>
Code for the registered user:
Register user:
<?php
$errors = [];
$missing = [];
if($_SERVER['REQUEST_METHOD'] == "POST"){
$username = $_POST["username"];
$password = $_POST["password"];
$firstname = $_POST["name"];
$lastName = $_POST["lastName"];
$email = $_POST["email"];
$month = $_POST["month"];
$day = $_POST["day"];
$year = $_POST["year"];
$gender = $_POST["gender"];
if (!isset($_POST['username']) || strlen($_POST['username']) < 3) {
$missing[] = "username";
}else{
}
if (!isset($_POST['name']) || strlen($_POST['name']) < 3) {
$missing[] = "name";
}else{
}
if (!isset($_POST['lastName'])|| strlen($_POST['lastName']) < 3) {
$missing[] = "lastName";
}
if (!isset($_POST['email']) || strlen($_POST['email']) < 3 ) {
$missing[] = "email";
}
if (!isset($_POST['re-password']) || strlen($_POST['re-password']) < 3 ) {
$missing[] = "re-password";
}
if (!isset($_POST['password']) || strlen($_POST['password']) < 3 ) {
$missing[] = "password";
}
if (!isset($_POST['month']) || $_POST['month'] == "Month" ) {
$missing[] = "month";
}
if (!isset($_POST['year']) || $_POST['year'] == "Year" ) {
$missing[] = "year";
}
if (!isset($_POST['day']) || $_POST['day'] == "Day") {
$missing[] = "day";
}
if (!isset($_POST['gender'])) {
$missing[] = "Select gender";
}
if(count($missing) > 0){
echo "validation error!!!";
}else{
$dsn = "mysql:host=";
$host = "localhost";
$db = "registration";
$dsn .= $host.";";
$dsn .= "dbname=".$db;
$user = 'root';
$dbh = new PDO($dsn, $user);
$selectQuery = "SELECT * FROM register_table WHERE username = :username OR email_adress = :email";
$stmt = $dbh->prepare($selectQuery);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();
if($stmt->rowCount() > 0){
echo "User exists!!!";
}else{
$stmtInsert = $dbh->prepare("INSERT INTO register_table (username, password, first_name, last_name, email_adress, month, day, year, gender) VALUES (:username, :password, :name, :lastName, :email, :month, :day, :year, :gender)");
$stmtInsert->bindParam(':username', $username);
$stmtInsert->bindParam(':password', $password);
$stmtInsert->bindParam(':name', $firstname);
$stmtInsert->bindParam(':lastName', $lastName);
$stmtInsert->bindParam(':email', $email);
$stmtInsert->bindParam(':month', $month);
$stmtInsert->bindParam(':day', $day);
$stmtInsert->bindParam(':year', $year);
$stmtInsert->bindParam(':gender', $gender);
$stmtInsert->execute();
$arr = $stmtInsert->errorInfo();
print_r($arr);
echo "New records created successfully!!!";
}
$editQuery = "SELECT username FROM register_table";
$editResult = mysql_query($editQuery);
while($user = mysql_fetch_array($editQuery))
$dbh = null;
}
}
This is code I use on my database 2 sets of code - view.php displays the records with an option to edit next to each record in the list then if you click on edit it opens edit.php displaying a form to change and save the details. If you need it I can send the table structure and contents as well. There is quite a lot of code but I want to give the whole picture of a working system that I think does exactly what you want. It is mysql but I am converting to mysqli
view.php
<!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>Untitled Document</title>
</head>
<body>
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include('connect-db.php');
// get results from database
$result = mysql_query("SELECT * FROM stats")
or die(mysql_error());
// display data in table
echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>date</th> <th>Home Team</th> <th></th><th></th><th>Away Team</th> <th></th> <th></th> </tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['date'] . '</td>';
echo '<td>' . $row['hometeam'] . '</td>';
echo '<td>' . $row['fthg'] . '</td>';
echo '<td>' . $row['ftag'] . '</td>';
echo '<td>' . $row['awayteam'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
edit.php
<!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>Untitled Document</title>
</head>
<body>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// 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, $hometeam, $awayteam, $error)
{
// 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>First Name: *</strong> <input type="text" name="hometeam" value="<?php echo $hometeam; ?>"/><br/>
<strong>Last Name: *</strong> <input type="text" name="awayteam" value="<?php echo $awayteam; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.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 = $_POST['id'];
$hometeam = mysql_real_escape_string(htmlspecialchars($_POST['hometeam']));
$awayteam = mysql_real_escape_string(htmlspecialchars($_POST['awayteam']));
// check that hometeam/awayteam fields are both filled in
if ($hometeam == '' || $awayteam == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $hometeam, $awayteam, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE stats SET hometeam='$hometeam', awayteam='$awayteam' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.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 stats 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
$hometeam = $row['hometeam'];
$awayteam = $row['awayteam'];
// show form
renderForm($id, $hometeam, $awayteam, '');
}
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!';
}
}
?>
</body>
</html>
Related
I am struggling to get my PHP unit converter to work.
I am trying to get multiple converters going but cant seem to get it working.
It'd be great if someone could show me where I'm going wrong and help me get it going. :)
<?php
if($_POST){
$fahrenheit = $_POST['fahrenheit'];
$celsius = ($fahrenheit - 32)*5/9;
}
if($_POST){
$celsius = $_POST['celcius'];
$fahrenheit = ($celcius - 32)*5/9;
}
?>
<form action="" method="post">
Fahrenheit: <input type="text" name="fahrenheit" /><br />
<?php
if(isset($celsius)){
echo "Celsius = ".$celsius;
}
?>
</form>
<?php
function fahrenheit_to_celsius($given_value)
{
$celsius=5/9*($given_value-32);
return $celsius ;
}
function celsius_to_fahrenheit($given_value)
{
$fahrenheit=$given_value*9/5+32;
return $fahrenheit ;
}
function inches_to_centimeter($given_value)
{
$centimeter=$given_value/2.54;
return $centimeter ;
}
function centimeter_to_inches($given_value)
{
$inches=$given_value*2.54
}
?>
<html>
<head>
<title>Temp. Conv.</title>
</head>
<body>
<form action="" method="post">
<table>
<!-- FAHRENHEIGHT & CELCIUS V -->
<tr>
<td>
<select name="first_temp_type_name">
<option value="fahrenheit">Fahrenheit</option>
<option value="celsius">Celsius</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<tr>
<td>
<select name="second_temp_type_name">
<option value="fahrenheit">Fahrenheit</option>
<option value="celsius">Celsius</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" name="btn" value="Convert">
</td>
</tr>
<!--FAHRENHEIGHT & CELCIUS ^ -->
<!-- CENTEMETERS & INCHES -->
<tr>
<td>
<select name="first_length_type_name">
<option value="centimeter">centimeter</option>
<option value="inches">Inches</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<tr>
<td>
<select name="second_length_type_name">
<option value="centimeter">centimeter</option>
<option value="inches">Inches</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<!--CENTEMETERS & INCHES ^-->
<tr>
<td>
<?php
if(isset($_POST['btn']))
{
$first_temp_type_name=$_POST['first_temp_type_name'];
$second_temp_type_name=$_POST['second_temp_type_name'];
$given_value=$_POST['given_value'];
if($first_temp_type_name=='fahrenheit')
{
$celsious=fahrenheit_to_celsius($given_value);
echo "Fahrenheit $given_value = $celsious Celsious";
}
if($first_temp_type_name=='celsius')
{
$fahrenheit=celsius_to_fahrenheit($given_value);
echo "Celsious $given_value = $fahrenheit Fahrenheit";
}
}
if(isset($_POST['btn']))
{
$first_length_type_name=$_POST['first_length_type_name'];
$second_length_type_name=$_POST['second_length_type_name'];
$given_value=$_POST['given_value'];
if($first_length_type_name=='centimeter')
{
$centimeter=centimeter_to_inches($given_value);
echo "Centimeter $given_value = $inches Inches";
}
if($first_length_type_name=='inches')
{
$centimeter=inches_to_centimeter($given_value);
echo "Inches $given_value = $centimeter centimeter";
}
}
?>
</td>
</tr>
</table>
</form>
</body>
</html>
I know there is a lot going on, my apologies.
Any help is greatly appreciated :)
Hi please use the following code.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$convertedTemperature = 0;
/* The condition is entered when the request is of POST type. */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$temperature = $_POST['temperature'];
$fromConvertionUnit = $_POST['fromConvertionUnit'];
$toConvertionUnit = $_POST['toConvertionUnit'];
/* if the temperature conversion are of same unit then no need for conversion */
if($fromConvertionUnit == $toConvertionUnit){
$convertedTemperature = $temperature;
}else if($fromConvertionUnit == 'fahrenheit' && $toConvertionUnit == 'celcius') {
/* formula to convert Fahrenheit to Celcius */
$convertedTemperature = ($temperature - 32) * 0.5556;
}else if($fromConvertionUnit == 'celcius' && $toConvertionUnit == 'fahrenheit') {
/* formula to convert Celcius to Fahrenheit */
$convertedTemperature = ($temperature * 1.8) + 32;
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Temperature Converter</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<div>
<!-- If the temperature value has be submitted and has data then it will prefilled -->
<label for="temperature">Temperature</label> <br/>
<input type="number" name="temperature" id="temperature" value="<?php echo (!empty($temperature)) ? $temperature : '' ?>">
</div>
<div>
<label for="fromConvertionUnit">Select From Convertion Unit</label><br/>
<select name="fromConvertionUnit" id="fromConvertionUnit">
<option value="fahrenheit">Fahrenheit</option>
<option value="celcius">Celcius</option>
</select>
</div>
<div>
<label for="toConvertionUnit">Select To Convertion Unit</label><br/>
<select name="toConvertionUnit" id="toConvertionUnit">
<option value="fahrenheit">Fahrenheit</option>
<option value="celcius">Celcius</option>
</select>
</div>
<!-- Once the page is submitted and conversion is done the respective values will be added in the following section -->
<div>
Converted Temperature <b> <?php echo (!empty($temperature)) ? $temperature : '--' ?></b> Value From <b><?php echo (!empty($fromConvertionUnit)) ? $fromConvertionUnit : '--' ?></b> TO <b><?php echo (!empty($toConvertionUnit)) ? $toConvertionUnit : '--' ?></b> is <b><?php echo (!empty($convertedTemperature)) ? $convertedTemperature : '--' ?><b/>
<label for="converted_value">Converted Value</label><br/>
<input type="number" value="<?php echo (!empty($convertedTemperature)) ? $convertedTemperature : '0' ?>">
</div>
<div>
<input type="submit" value="Convert">
</div>
</form>
</body>
</html>
If you want to make a converter, all you need is one input - and a dropdown between what you wish to convert to. Then use a switch in PHP when the form was submitted to check what function you wish to use.
Your current issue is that you overwrite a lot of values, and that you don't check for the right buttons. This is also over-complicating it.
You can further develop this converter by making sure that the input is an actual number - by using filter_var() with a flag that's suitable for your need. You can either validate it or sanitize it, see FILTER_SANITIZE vs FILTER VALIDATE, whats the difference - and which to use?.
<?php
if (isset($_POST['submit'])) {
switch ($_POST['convert']) {
case "cm-in":
$result = centimeter_to_inches($_POST['value']);
$old_unit = 'cm';
$new_unit = ' inches';
break;
case "in-cm":
$result = inches_to_centimeter($_POST['value']);
$old_unit = ' inches';
$new_unit = 'cm';
break;
case "f-c":
$result = fahrenheit_to_celsius($_POST['value']);
$old_unit = ' Farenheit';
$new_unit = ' Celcius';
break;
case "c-f":
$result = celsius_to_fahrenheit($_POST['value']);
$old_unit = ' Celcius';
$new_unit = ' Farenheit';
break;
}
}
function fahrenheit_to_celsius($given_value) {
return 5/9*($given_value-32);
}
function celsius_to_fahrenheit($given_value) {
return $given_value*9/5+32;
}
function inches_to_centimeter($given_value) {
return $given_value/2.54;
}
function centimeter_to_inches($given_value) {
return $given_value*2.54;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Conversions</title>
</head>
<body>
<form method="post">
Convert <input type="text" name="value" /><br />
<select name="convert">
<option value="">--Select one--</option>
<optgroup label="Units of Length">
<option value="cm-in">Centimeter to inches</option>
<option value="in-cm">Inches to centimeter</option>
</optgroup>
<optgroup label="Units of Temperature">
<option value="f-c">Farenheit to Celcius</option>
<option value="c-f">Celcius to Farenheit</option>
</optgroup>
</select>
<input type="submit" name="submit" value="Convert" />
</form>
<?php
if (!empty($result))
echo '<p>'.$_POST['value'].$old_unit.' equals '.$result.$new_unit.'</p>';
?>
</body>
</html>
I have created a form which allows users to edit existing data within a database, I pull information from one page to the next to populate text boxes and select boxes. I have managed to populate the select box with the correct value but when the update statement goes through it deletes or doesn't recognize the pre-existing value. Can anyone help?
if (isset($_POST['submit'])) {
// Process the form
if (empty($errors)) {
$id = $brand["brandId"];
$brandName = mysql_prep($_POST["brandName"]);
$brandCategory = mysql_prep($_POST["brandCategory"]);
$brandKeyword = mysql_prep($_POST["brandKeyword"]);
$addedBy = mysql_prep($_SESSION['username']);
$query = "UPDATE brands SET ";
$query .= "brandName = '{$brandName}', ";
$query .= "brandCategory = '{$brandCategory}', ";
$query .= "brandKeyword = '{$brandKeyword}', ";
$query .= "addedBy = '{$addedBy}', ";
$query .= "dateTime = CURRENT_TIMESTAMP ";
$query .= "WHERE brandId = '{$id}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Brand updated.";
redirect_to("search.php");
} else {
// Failure
$_SESSION["message"] = "Brand update failed.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
<?php $layout_context = "user"; ?>
<?php include("../includes/layouts/header.php"); ?>
<?php include("../includes/layouts/navigation.php"); ?>
<div class="section">
<div id="message">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
</div>
<form id="edit_brands" action="edit_brands.php?id=<?php echo urlencode($brand["brandId"]); ?>" method="post">
<h2>Edit Brand Information: <?php echo htmlentities($brand["brandName"]);?></h2>
<p>
<label for="bname">Brand Name:</label>
<input class="textbox" id="bname" type="text" name="brandName" value="<?php echo htmlentities($brand["brandName"]); ?>" autofocus/>
</p>
<p>
<label for="bcategory">Brand Category:</label>
<select class="textbox" id="bcategory" type="text" name="brandCategory">
<option value=""><?php echo htmlentities($brand["brandCategory"]); ?></option>
<option value="Animation">Animation</option>
<option value="Automotive">Automotive</option>
<option value="Beauty and Fashion">Beauty & Fashion</option>
<option value="Comedy">Comedy</option>
<option value="Cooking and Health">Cooking & Health</option>
<option value="DIY">DIY</option>
<option value="Fashion">Fashion</option>
<option value="Film and Entertainment">Film & Entertainment</option>
<option value="Food and Drink">Food & Drink</option>
<option value="Gaming">Gaming</option>
<option value="Lifestyle">Lifestyle</option>
<option value="Music">Music</option>
<option value="News and Politics">News & Politics</option>
<option value="Science&Education">Science & Education</option>
<option value="Sports">Sports</option>
<option value="Technology">Technology</option>
<option value="Television">Television</option>
</select>
</p>
<p>
<label for="bkeyword">Brand Keyword:</label>
<textarea class="FormElement" id="bkeyword" name="brandKeyword" id="brandKeyword" placeholder=""><?php echo htmlentities($brand["brandKeyword"]); ?></textarea>
</p>
<p>
<input type="submit" class="button" name="submit" value="Edit Brand" onclick="return confirm('Do you wish to edit brand?');"/>
</p>
<p>
Cancel
</p>
</form>
</div>
</div>
The best way is to build the select from an array.
For instance:
<?php
$array = array('Animation', 'Automotive', 'Beauty and Fashion ', ...);
echo '<select class="textbox" id="bcategory" type="text" name="brandCategory">';
foreach ($array as $value){
if($value == htmlentities($brand["brandCategory"]){
echo '<option value='.$value.' selected>'.$value.'</option>';
}else{
echo '<option value='.$value.'>'.$value.'</option>';
}
}
echo '</select>;
This way you can check if the value in the array is the same that the one recieved by post and then add the selected attribute to the option tag.
I found this site providing code for creating, reading, updating and deleting. I am confused about how to add checkboxes, radio buttons, and dropdowns
http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
I'm not concerned with the pagination at all——my primary concern is to be able to put in two dropdowns, yes/no radio button, and a collection of 3 checkboxes using PHP.
My attempts were useless as when I tried to edit choices the values did not stay. Included are my three files: pets, editpets, and view.(I changed the file name for database, etc.)
<?php
function renderForm($first, $last, $pets, $size, $type, $years, $error)
{
?>
<!DOCTYPE html>
<html>
<head>
<title>New Customer</title>
</head>
<body>
<?php
// display possible errors
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>First Name:</strong> <input type="text" name="firstname" value="<?php echo
$first; ?>" />
<strong>Last Name:</strong> <input align="center" type="text" name="lastname" value="<
?php echo $last; ?>" /><br/>
<p><strong>No. Pets </strong>
<select name="pets">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</p>
<br/>
<strong>Size? </strong>
<br/>
Big<input type="radio" value="Yes" name="size" checked><?php echo $size; ?><br />
Small<input type="radio" value="No" name="size"<?php echo $size; ?><br />
<br />
<p><strong>Type</strong><br/>
<input name="type[]" type="checkbox" id="type[]"/>
Cats
<input name="type[]" type="checkbox" id="type[]"/>
Dogs
<input name="type[]" type="checkbox" id="type[]"/>
Others
</p>
<br/>
<strong>Years? </strong>
<select name="year">
<option value="Five or Less">Five or More</option>
<option value="Six or More">Six or More</option>
</select><br/>
<input style="color:purple;" type="submit" name="submit" value="Create My Order :-)">
</div>
</form>
<center>Click Here for Orders</center>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if my form submits and, upon triumph, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, check its validity
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$pets = $_POST['pets'];
$size = mysql_real_escape_string(htmlspecialchars($_POST['size']));
$type = serialize(mysql_real_escape_string(implode(',', $_POST['type'])));
$years = mysql_real_escape_string(htmlspecialchars($_POST['years']));
// check to make sure everything is filled!
if ($firstname == '' || $lastname == '' || $pets == '' || $size == '' || $type == '' || $years == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, show the form again
renderForm($firstname, $lastname, $pets, $size, $type, $years, $error);
}
else
{
// save the data to the database
mysql_query("INSERT customers SET firstname='$firstname', lastname='$lastname', pets='$pets', size='$size', type='$type', years='$years'")
or die(mysql_error());
// once saved, redirect to cheview page
header("Location: view.php");
}
}
else
// if the form is not submitted, show my form again.
{
renderForm('','','','','','','');
}
?>
<?php
$types = array("Cats", "Dogs", "Others");
function renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<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>First Name: </strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>" /><br/>
<strong>Last Name: </strong> <input type="text" name="lastname" value="<?php echo $lastname; ?>" /><br/>
<p><strong>No. Pets </strong>
<select name="pets">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</p>
<strong>Size? </strong>
<br/>
Big<input type="radio" value="Yes" name="size" checked><?php echo $size; ?><br />
Small<input type="radio" value="No" name="size"<?php echo $size; ?><br />
<br />
<br />
<br />
<p><strong>Type</strong><br/>
<input name="type[]" type="checkbox" id="type[]"/>
Cats
<input name="type[]" type="checkbox" id="type[]"/>
Dogs
<input name="type[]" type="checkbox" id="type[]"/>
Others
</p>
<br/>
<strong>Years? </strong>
<select name="year">
<option value="Five or Less">Five or More</option>
<option value="Six or More">Six or More</option>
</select><br/>
<br /><br />
<input type="submit" name="submit" value="Resubmit My Order :-)">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// check for id being an integer
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$pets = $_POST['pets'];
$size = mysql_real_escape_string(htmlspecialchars($_POST['size']));
$type = serialize(mysql_real_escape_string(implode(',', $_POST['type'])));
$years = mysql_real_escape_string(htmlspecialchars($_POST['years']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $lastname == '' || $pets == '' || $size == '' || $type == '' || $years == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE customers SET firstname='$firstname', lastname='$lastname', pets='$pets', size='$size', type='$type', years='$years' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.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 customers 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
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$pets = $row['pets'];
$size = $row['size'];
$type = serialize($row['type']);
$years = $row['years'];
// show form
renderForm($id, $firstname, $lastname, $pets, $size, $type, $years, '');
}
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!';
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View customer orders</title>
</head>
<body>
<?php
include('connect-db.php');
$result = mysql_query("SELECT * FROM customers")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Pets</th>
<th>Size</th>
<th>Type</th>
<th>Years</th>
<th></th>
<th></th>
</tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td>' . $row['pets'] . '</td>';
echo '<td>' . $row['size'] . '</td>';
echo '<td>' . $row['type']. '</td>';
echo '<td>' . $row['years'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
I'm honestly lost at this point. I've been working on this for an entire month and I have no idea what I'm doing any more. I'd be so thankful if anyone can help me to edit this to work.
Thanks everyone.
Right, to get your saved results from the database I'm sure you're aware of how to do this.
For your radio buttons you're going to want to select your 'size' value from the database and use an if statement to determine which radio button will be 'checked'
forename/surname is a matter of simply getting the forename/surname from database and setting the appropriate input tags to the acquired values
You've already posted a technique for handling the combo/drop-down boxes
you'd perform a similar process for the 'type' checkboxes, compare your database values to the values of your checkbox input tags and if the value matches, set the checkbox to checked.
Next time please be more specific in what you are asking for help with and separate your code into segments that correspond with the files it is contained in.
if you have 3 files, have a code block for each file.
I have set up a form which has a tick box on it as well as a few textareas to enter comments. I want the user to have to complete the textarea(tutorComment) if they tick the tickbox(alert)
EDIT : Here is my complete code
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] )){
echo "<h3>You must enter a reason why you have clicked the alert box</h3>";
exit();}
This worked fine until I added this bit of code at the top of my php
if(isset($_REQUEST['submited']))
Can i not use the isset twice? I'm a bit confused as to why the code has stopped working
Thanks in advance
Here is the complete code
<! Code to check that the user has logged into to view this page !>
<!Connection details for connecting to mysql database!>
<?php
//Select which database you want to connect to
<!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>Op Tech Database - Add Record</title>
</head>
<!Code to Create drop down menu's!>
<?php
//Code for collectiing values for Student Names drop down drop
$result1=mysql_query("SELECT studentID, studentName FROM students");
$options1="";
while ($row=mysql_fetch_array($result1)) {
$id=$row["studentID"];
$first=$row["studentName"];
$options1.="<OPTION VALUE=\"$first\">".$first.'</option>';
}
//Code for getting tutors names in drop down list
$result2=mysql_query("SELECT staffID, tutorName FROM staff");
$options2="";
while ($row=mysql_fetch_array($result2)) {
$id=$row["staffID"];
$first=$row["tutorName"];
$options2.="<OPTION VALUE=\"$first\">".$first.'</option>';
}
?>
<body>
<link rel="stylesheet" type="text/css" href="ex1.css" >
<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="ipad.css" type="text/css" />
<!Create HTML elements!>
<form name="myform" form method="post">
<h1 align="center"><img src="colour_logo_400.jpg" alt="University Logo" width="400" height="185" /></h1>
<h1 align="center">Dental Hygiene Operative Technique Database</h1>
<h2 align="center">Welcome to the Dental Hygiene Operative Technique Database v1</h2>
<p align="left"> </p>
<p align="left">Student Name</p>
<p align="left">
<! Drop Down Menu to get student names from database !>
<SELECT NAME=studentName >
<OPTION VALUE=0 selected="selected">
<?php echo $options1?>
</SELECT>
<p align="left">Tutor Name
<p align="left">
<! Drop Down Menu to get tutor names from database !>
<select name=tutorName>
<option value=0>
<?php echo $options2 ?> </option>
</select>
<p align="left">
<p align="left"><br>
Procedure
<input type="text" name="procedure" value="<?php if(isset($_POST['procedure'])) echo $_POST['procedure'];?>" />
<select name=grade id=grade>
<option value="">Grade </option>
<option value="N" <?php if (isset($_POST['grade']) && $_POST['grade'] == "N") { echo 'selected="selected"';} ?>>N</option>
<option value="B" <?php if (isset($_POST['grade']) && $_POST['grade'] == "B") { echo 'selected="selected"';} ?>>B</option>
<option value="C" <?php if (isset($_POST['grade']) && $_POST['grade'] == "C") { echo 'selected="selected"';} ?>>C</option>
</select>
<p align="left">
Student Reflection:
<br>
<textarea name="studentReflection" cols="75" rows="5"><?php if(isset($_POST['studentReflection'])) echo $_POST[ 'studentReflection'];?></textarea>
<p align="left">
<SELECT NAME=professionalism>
<OPTION VALUE="">Professionalism
<OPTION VALUE="U" <?php if (isset($_POST['professionalism']) && $_POST['professionalism'] == "U") {
echo 'selected="selected"';} ?>>U</option>
<OPTION VALUE="S" <?php if (isset($_POST['professionalism']) && $_POST['professionalism'] == "S") {
echo 'selected="selected"';} ?>>S</option>
<OPTION VALUE="E" <?php if (isset($_POST['professionalism']) && $_POST['professionalism'] == "E") {
echo 'selected="selected"';} ?>>U</option>
</SELECT>
</SELECT>
<SELECT NAME=communication>
<OPTION VALUE="">Communication
<OPTION VALUE="U" <?php if (isset($_POST['communication']) && $_POST['communication'] == "U") {
echo 'selected="selected"';} ?>>U</option>
<OPTION VALUE="S" <?php if (isset($_POST['communication']) && $_POST['communication'] == "S") {
echo 'selected="selected"';} ?>>S</option>
<OPTION VALUE="E" <?php if (isset($_POST['communication']) && $_POST['communication'] == "E") {
echo 'selected="selected"';} ?>>U</option>
</SELECT>
Alert:
<input type="checkbox" value="YES" name="alert" >
<br>
<br>
Tutor Comments:<br>
<textarea name="tutorComments" cols="75" rows="5"><?php if(isset($_POST['tutorComments'])) echo $_POST['tutorComments'];?>
</textarea>
<p align="left">
<!Submit buttons for the form!>
<input type="hidden" name="submited" value="true" />
<input type="submit" value="Update Database" name="submit"/>
<input type='button' value='Logout' onClick="window.location.href='http://address/php_sandbox/optech/dh/current/14june/logout.php'">
<p align="left">
<?php
//Error Message to display if all the correct fields are not completed.
if(isset($_REQUEST['submited'])) {
$errorMessage = "This is the standard error message";
$options1 = $_POST['studentName'];
$options2 = $_POST['tutorName'];
$procedure = $_POST['procedure'];
$grade = $_POST['grade'];
$studentReflection = $_POST['studentReflection'];
$professionalism = $_POST['professionalism'];
$communication = $_POST['communication'];
$tutorComments = $_POST ['tutorComments'];
if(empty($_POST['alert']))
{
$_POST['alert'] = "NO";
}
$alert = $_POST['alert'] ;
//Code to check that the Student Name field is completed
if(empty($_POST['studentName']))
{
echo "<h3>You have not selected a student. Please go back and do so!</h3>";
exit();
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
echo "<h3>You did not select a tutor name. Please go back and select your name from the tutors list</h3>";
exit();
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
echo "<h3>You did not select a procedure. Please go back and enter the name of the procedure which you undertook</h3>";
exit();
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
echo "<h3>You did not select a grade. Please go back and select your grade from the drop down list</h3>";
exit();
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
echo "<h3>The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments</h3>";
exit();
}
//Code to check if the tick box is checked that the tutor comment is entered
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] )){
echo "<h3>You must enter a reason why you have clicked the alert box</h3>";
exit();
}
//Code to connect to the database
$query= "INSERT INTO entry (entryID, studentName , tutorName , procedureName , grade , studentReflection , tutorComments, professionalism , communication , alert ) VALUES ('NULL', '".$options1."' , '".$options2." ' , '".$procedure."' , '".$grade."' , '".$studentReflection."', '".$tutorComments."' , '".$professionalism."' , '".$communication."' , '".$alert."' )";
mysql_query($query) or die ('Error : Something fucked up' .mysql_error());
echo "<h3>The Database Has been updated. Thanks </h3></b>" ;
}
?>
</FORM>
<p> Enter another procedure
<p> </p>
<p> </p>
</body>
</html>
That's a lot of code, I can't say what exactly but some possible problems to look at:
looks like you're missing a '?>' at the top, on line before the DOCTYPE etc.
Form has no action="" so put the name of the current php file or $_SERVER['PHP_SELF']
student names option and alert input don't have closing tags
Try doing the isset on the submit button instead, no need for the hidden input:
if(isset($_REQUEST['submit'])) {or if(isset($_POST['submit'])) {
If it's still not working try moving that whole block of code to the top before outputting the form.
Instead of using empty() for this, just check that it's set or not:
if(isset($_POST['alert']))
$alert = $_POST['alert'];
else
$alert = "";
or for short: $alert = isset($_POST['alert'])?$_POST['alert']:"";
Instead of this:
if( !strlen($_POST['tutorComments'])
&& isset($_POST['alert'] )){
echo "You must enter a reason why you have clicked the alert box";
exit();
}
write it like this:
if(isset($_POST['alert'])){
if(!strlen($_POST['tutorComments']))
echo "You must enter a reason why you have clicked the alert box";
// leave out the exit()
}
or try different tests such as: if(strlen($_POST['tutorComments'])< 1) etc.
I have created a form which has a number of fields which I am posting to a database.
At the bottom of the form I I have set some simply error checking to make sure all the required fields are complete.
When the user clicks the submit button my error checking take place and if there are errors it will output a string with the errors which it encountered.
These errors are currently displayed below the form but I want them to appear above the form fields. Is there anyway I can do this?
If I move the error checking code above the form field obviosly it does not work as it checks for errors before any of the field have been completed.
Any ideas how I can do this?
Here is the code
enter code here
<! Code to check that the user has logged into to view this page !>
<?php
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login.php");
}
?>
<!Connection details for connecting to mysql database!>
<!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>Op Tech Database - Add Record</title>
</head>
<!Code to Create drop down menu's!>
<?php
//Code for collectiing values for Student Names drop down drop
$result1=mysql_query("SELECT studentID, studentName FROM students");
$options1="";
while ($row=mysql_fetch_array($result1)) {
$id=$row["studentID"];
$first=$row["studentName"];
$options1.="<OPTION VALUE=\"$first\">".$first.'</option>';
}
//Code for getting tutors names in drop down list
$result2=mysql_query("SELECT staffID, tutorName FROM staff");
$options2="";
while ($row=mysql_fetch_array($result2)) {
$id=$row["staffID"];
$first=$row["tutorName"];
$options2.="<OPTION VALUE=\"$first\">".$first.'</option>';
}
if(isset($_REQUEST['submited'])) {
$errorMessage = "This is the standard error message";
$options1 = $_POST['studentName'];
$options2 = $_POST['tutorName'];
$procedure = htmlspecialchars($_POST['procedure']);
$grade = $_POST['grade'];
$studentReflection = htmlspecialchars($_POST['studentReflection']);
$professionalism = $_POST['professionalism'];
$communication = $_POST['communication'];
$tutorComments = htmlspecialchars($_POST ['tutorComments']);
/*if(empty($_POST['alert']))
{
$_POST['alert'] = "NO";
}
*/
$alert = $_POST['alert'] ;
$studentNameError = "You did not enter the student name";
$error = false;
if(empty($_POST['studentName']))
{
$studentNameError = "You did not enter the student name";
echo "<h3> $studentNameError </h3>";
$error = true;
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
echo "<h3>You did not select a tutor name.</h3>";
$error = true;
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
echo "<h3>You did not select a procedure.k</h3>";
$error = true;
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
echo "<h3>You did not select a grade.</h3>";
$error = true;
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
echo "<h3>The student did not enter any comments for this procedure. Student reflection is required for each procedure. </h3>";
$error = true;
}
//Code to check if the tick box is checked that the tutor comment is entered
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
{
echo "<h3>You must enter a reason why you have clicked the alert box</h3>";
$error = true;
}
if($error)
{
exit();
}
?>
<body>
<link rel="stylesheet" type="text/css" href="ex1.css" >
<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="ipad.css" type="text/css" />
<!Create HTML elements!>
<form name="myform" form method="post">
<h1 align="center"><img src="colour_logo_400.jpg" alt="University Logo" width="400" height="185" /></h1>
<h1 align="center">Dental Hygiene Operative Technique Database</h1>
<h2 align="center">Welcome to the Dental Hygiene Operative Technique Database v1</h2>
<p align="left"> </p>
<p align="left">Student Name(*)</p>
<p align="left">
<! Drop Down Menu to get student names from database !>
<SELECT NAME=studentName >
<OPTION VALUE=0 selected="selected" >
<?php if(isset($_POST['studentName'])) echo $_POST['studentName'];?>
<?php echo $options1?>
</SELECT>
<p align="left">Tutor Name
(*)<p align="left">
<! Drop Down Menu to get tutor names from database !>
<select name=tutorName>
<option value=0>
<?php if(isset($_POST['tutorName'])) echo $_POST['tutorName'];?>
<?php echo $options2 ?> </option>
</select>
<p align="left">
<p align="left"><br>
Procedure(*)
<input type="text" name="procedure" value="<?php if(isset($_POST['procedure'])) echo $_POST['procedure'];?>" />
<select name=grade id=grade>
<option value="">Grade </option>
<option value="N" <?php if (isset($_POST['grade']) && $_POST['grade'] == "N") { echo 'selected="selected"';} ?>>N</option>
<option value="B" <?php if (isset($_POST['grade']) && $_POST['grade'] == "B") { echo 'selected="selected"';} ?>>B</option>
<option value="C" <?php if (isset($_POST['grade']) && $_POST['grade'] == "C") { echo 'selected="selected"';} ?>>C</option>
</select>
(*)
<p align="left">
Student Reflection:
(*)<br>
<textarea name="studentReflection" cols="75" rows="5"><?php if(isset($_POST['studentReflection'])) echo $_POST[ 'studentReflection'];?></textarea>
<p align="left">
<SELECT NAME=professionalism>
<OPTION VALUE="">Professionalism
<OPTION VALUE="U" <?php if (isset($_POST['professionalism']) && $_POST['professionalism'] == "U") {
echo 'selected="selected"';} ?>>U</option>
<OPTION VALUE="S" <?php if (isset($_POST['professionalism']) && $_POST['professionalism'] == "S") {
echo 'selected="selected"';} ?>>S</option>
<OPTION VALUE="E" <?php if (isset($_POST['professionalism']) && $_POST['professionalism'] == "E") {
echo 'selected="selected"';} ?>>U</option>
</SELECT>
</SELECT>
<SELECT NAME=communication>
<OPTION VALUE="">Communication
<OPTION VALUE="U" <?php if (isset($_POST['communication']) && $_POST['communication'] == "U") {
echo 'selected="selected"';} ?>>U</option>
<OPTION VALUE="S" <?php if (isset($_POST['communication']) && $_POST['communication'] == "S") {
echo 'selected="selected"';} ?>>S</option>
<OPTION VALUE="E" <?php if (isset($_POST['communication']) && $_POST['communication'] == "E") {
echo 'selected="selected"';} ?>>U</option>
</SELECT>
Alert:
<input type="checkbox" value="YES" name="alert" >
<br>
<br>
Tutor Comments:
<br>
<br>
<textarea name="tutorComments" cols="75" rows="5">
<?php if(isset($_POST['tutorComments'])) echo $_POST['tutorComments'];?></textarea>
<p align="left">
<!Submit buttons for the form!>
<input type="submit" name="mattbutton" class="mattbutton" value="Update Database" name="submit"/>
<input type='button' name="mattbutton" class="mattbutton" value='Logout' onClick="window.location.href='logout.php'">
<input type="hidden" name="submited" value="true" />
<p align="left">
<?php
//Code to turn off error reporting
//error_reporting(0);
//Error Message to display if all the correct fields are not completed.
//Code to connect to the database
$query= "INSERT INTO entry (entryID, studentName , tutorName , procedureName , grade , studentReflection , tutorComments, professionalism , communication , alert ) VALUES ('NULL', '".$options1."' , '".$options2." ' , '".$procedure."' , '".$grade."' , '".$studentReflection."', '".$tutorComments."' , '".$professionalism."' , '".$communication."' , '".$alert."' )";
mysql_query($query) or die ('Error : You are attempting to enter information which cannot be stored or contains code. Please refesh the from and try again<br>' .mysql_error());
echo "<h3>The Database Has been updated. Thanks </h3></b>" ;
}
?>
</FORM>
<p> Enter another procedure
<p> </p>
<p> </p>
</body>
</html>
There shouldn't be any problem having your error checking code "above" the form rendering code. Once the form has been submitted, presumably via POST, you have all of the form variables in an array (the $_POST array) and they can be used regardless of whether or not you decide to re-render the form or not.
You can make a hidden field in your form, for example
<input type="hidden" name="isSubmitted" value ="1">
Then, in your checking routines, you first check if $_POST['isSubmitted'] (or $_GET['isSubmitted']) == 1 If it's true, then you know that user have been submitted your form, and you can make your additional checks