Validating PHP form fields - php

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.

Related

How to retrieve values from SQLite 3 database on the basis of multiple check boxes selected at once in PHP?

I am new to PHP coding. I have different preferences for the user to select from my html page. I want to retrieve all the check boxes selected by the user and display the hotel names which have all those preferences in them. For example if a user selects "Roof top", "Sea side" and "Swimming pool" check boxes, then the hotels against which their is a 1 placed in the respective columns in the mytrip.db database must be retrieved all at once and get displayed. My code takes only one checkbox value and displays the hotel name against that only. I want to display the hotels that contain all the preferences.
My code is below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP: Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP: Get Values of Multiple Checked Checkboxes</h2>
<select id="mySelect" name="list">
<option selected>Select a place</option>
<option value="1">Lahore</option>
<option value="2">Dubai</option>
<option value="3">New York</option>
<option value="4">Canberra</option>
<option value="5">London</option>
</select>
<form action="php_checkbox.php" method="post">
<label class="heading">Select Your Preferences:</label>
<input type="checkbox" name="check_list[]" value="Swimming pool"><label>Swimming pool</label>
<input type="checkbox" name="check_list[]" value="Roof top"><label>Roof top</label>
<input type="checkbox" name="check_list[]" value="Sea side"><label>Sea side</label>
<input type="submit" name="submit" Value="Submit"/>
</html>
<?php include 'checkbox_value.php';?>
</form>
</div>
</div>
</body>
</html>
checkbox_value.php code is below:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mytrip.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
$prefarray=array();
$i=0;
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected) {
$prefarray[$i]= $selected;
echo "<p>".$prefarray[$i] ."</p>";
echo "<p>".$selected ."</p>";
$i++;
}
echo "<p>".$i ."</p>";
$sql =<<<EOF
SELECT hotel_name from Dubai WHERE $prefarray[i]==1 AND $prefarray[i-1]==1 ;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
}
else{
echo "<b>Please Select Atleast One Option.</b>";
}
}
?>
The problem with this code is that it only displays one checkbox value if I use query
SELECT hotel_name FROM Dubai WHERE $selected==1
I tried to save the check box values selected by making an array "prefarray". But when I execute the query that I have posted in my checkbox_value.php code it gives me error of "Undefined offset 3 in prefarray". I want the data base query to have only those checkbox values that have been selected by the user. For example if the user has selected 2 out of three checkboxes then my query should look like
SELECT hotel_name FROM Dubai WHERE $checkbox==1 AND $checkbox2==1;
Any help to achieve two of these tasks will be appreciated!
I have fixed and refactored (couldn't stop myself) your code.
I have changed column names to proper ones. There was some redundant code which did nothing so I got rid of it. The main thing you were looking for is concatenating each chosen column in foreach loop. I'm also checking selected values against hard coded $hotelOptions for protection against sql injection.
Here is what I got:
checkbox_value.php:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mytrip.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$hotelOptions = array('swimming_pool', 'roof_top', 'sea_side');
if (isset($_POST['submit'])) {
if (!empty($_POST['check_list']) && is_array($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
// Loop to store and display values of individual checked checkbox.
$where = '';
foreach($_POST['check_list'] as $selected) {
echo "<p>".$selected ."</p>";
if (array_search($selected, $hotelOptions) !== false) {
$where .= " AND {$selected} = 1";
}
}
$where = substr($where, 5, strlen($where));
$sql = "SELECT hotel_name FROM Dubai WHERE {$where};";
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
} else {
echo "<b>Please Select Atleast One Option.</b>";
}
}
html layout:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>PHP: Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css"/>
</head>
<body>
<div class="container">
<div class="main">
<form action="checkbox_value.php" method="post">
<h2>PHP: Get Values of Multiple Checked Checkboxes</h2>
<select id="mySelect" name="list">
<option selected>Select a place</option>
<option value="1">Lahore</option>
<option value="2">Dubai</option>
<option value="3">New York</option>
<option value="4">Canberra</option>
<option value="5">London</option>
</select>
<p class="heading">Select Your Preferences:</p>
<input type="checkbox" name="check_list[]" value="swimming_pool" id="checkbox_1">
<label for="checkbox_1">Swimming pool</label>
<input type="checkbox" name="check_list[]" value="roof_top" id="checkbox_2">
<label for="checkbox_2">Roof top</label>
<input type="checkbox" name="check_list[]" value="sea_side" id="checkbox_3">
<label for="checkbox_3">Sea side</label>
<div>
<input type="submit" name="submit" Value="Submit"/>
</div>
<?php include 'checkbox_value.php';?>
</form>
</div>
</div>
</body>
</html>

How to edit files from database?

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>

How to display alert message after submitting form

I want to display alert message of language selected. Disply alert message after submission of form.Below the code.I want to display alert message of language selected after.How can i do this?
<?php
global $mysqli;
$lang="Select `prompt_language` FROM `account_detail` WHERE `org_id`='36'";
$res= $mysqli->query($lang) or die($mysqli->error);
$row=$res->fetch_array(MYSQLI_ASSOC);
if($_POST['submit']=="Save")
{
$language=$_POST['pbx_lan'];
if($language!="")
{
$query="update `account_detail` set `prompt_language`= '$language' WHERE `org_id`='36'";
$result = $mysqli->query($query) or die($mysqli->error);
$_SESSION['check_update'] = "1";
setcookie("msg","Language Successfully Updated",time()+5,"/");
header("location:".SITE_URL."index.php?view=view_service");
}
else
{
setcookie("err","No Language Selected.Please Select Language",time()+5,"/");
header("location:".SITE_URL."index.php?view=view_service");
}
}
?>
<div class="dashboard">
<h2>Select Language<h2>
<form action="<?php echo $PHP_SELF ?>" method="post" enctype="multipart/form-data" action="prompts.php" >
<select id="pbx_lan" name="pbx_lan" style="margin-left:5px width=1px" class="input validdid required" >
<option value="">Select</option>
<option value="en" <?php echo $row['prompt_language'] == "en" ? "selected=selected" : ""; ?>>English</option>
<option value="uk" <?php echo $row['prompt_language'] == "uk" ? "selected=selected" : ""; ?>>English(UK)</option>
</select><br></br>
<input type="submit" name="submit" id="sub" value="Save" class="btn" style="margin-left:5px" />
</form>
</div>
Place try the below code
echo '<script>
alert("You have selected '.$language.'");
window.location = "'.$SITE_URL.'index.php?view=view_service."
</script>';
//header("location:".SITE_URL."index.php?view=view_service");

php - After validation why my select tag data get cleared

I am doing PHP validations for my html values. However when PHP validation fails and I return back to the page, the select tag form data is cleared. Is there anyway to do save and reload the form data in php
<?php
$qualific=$passingyear="";
$qualificErr=$passingyearErr="";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
//qualification validations starts here
if(empty($_POST["qualif"]))
{
$qualificErr="* Qualification is Required";
$valid=false;
}
else
{
$qualific=test_input($_POST["qualif"]);
}
//qualification validations starts here
/*yearOfPassing validation starts here*/
if(empty($_POST["yearpass"]))
{
$passingyearErr="* Year Of Pass is Required";
$valid=false;
}
else
{
$passingyear=test_input($_POST["yearpass"]);
}
/*yearOfPassing validation starts here*/
//if valid then redirect
if($valid){
include 'database.php';
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=success.php">';
exit;
}
}
<form method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>Qualification<span class="error">*</span>:</label>
<select name="qualif">
<option label="Select"></option>
<option>Below SSC(10 Std)</option>
<option>SSC(10 Std) passed</option>
<option>HSC(12 Std) passed</option>
<option>Graduate</option>
<option>Post Graduate</option>
</select>
<span class="error"><?php echo $qualificErr?></span> <br />
<br />
<label>Year of passing<span class="error">*</span>: </label>
<select name="yearpass">
<option label="Select"></option>
<option>1975</option>
<option>1976</option>
<option>1977</option>
</select>
</form>
try <?php if($_POST["qualif"] == "<value>") echo "selected"; ?> in each option tag.
like
<option <?php if($_POST["qualif"] == "Below SSC(10 Std)") echo "selected"; ?>>Below SSC(10 Std)</option>
Currently you are using <option> without values.
Use like :
<option value="SSC" <?php if(isset($_POST['qualif']) && $_POST['qualif'] == 'SSC') { echo "selected"; } ?> >SSC</option>
your are missing value parameter inside <option>.
you need to add some code inside <option> tag
Please try following code hope this will solve the issue.
<select name="qualif">
<option label="Select"></option>
<option value="Below SSC(10 Std)" <?php if($qualific == 'Below SSC(10 Std)') {?> selected <?php } ?>>Below SSC(10 Std)</option>
<option value=">SSC(10 Std) passed" <?php if($qualific == '>SSC(10 Std) passed') {?> selected <?php } ?>>SSC(10 Std) passed</option>
<option value="HSC(12 Std) passed" <?php if($qualific == 'HSC(12 Std) passed') {?> selected <?php } ?>>HSC(12 Std) passed</option>
<option value="Graduate" <?php if($qualific == 'Graduate') {?> selected <?php } ?>>Graduate</option>
<option value="Post Graduate" <?php if($qualific == 'Post Graduate') {?> selected <?php } ?>>Post Graduate</option>
</select>
<span class="error"><?php echo $qualificErr?></span> <br />
<br />
<label>Year of passing<span class="error">*</span>: </label>
<select name="yearpass">
<option label="Select"></option>
<option value="1975" <?php if($passingyear == '1975') {?> selected <?php } ?>>1975</option>
<option value="1976" <?php if($passingyear == '1976') {?> selected <?php } ?>>1976</option>
<option value="1977" <?php if($passingyear == '1977') {?> selected <?php } ?>>1977</option>
</select>
You should use jquery
<script type="text/javascript">
$(document).ready(function()
{
$("#id").val("<?php echo $_POST['qualif']; ?>");
});
</script>

PHP Form - Error Message Placements

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

Categories