I have 2 problems. First problem is that it comes up with a notice stating roomChosen is undefined, this is a php error, and second of all, it doesn;t show a javascript error if room number in textbox does not match with a room number in database.
Please look at the application here: application
enter in 'info101' in the courseId text box and then click submit. You will see all features in the page. At bottom you will see a "Prepare Questions" button, click it and you will see all validation messages including an empty room textbox below. Now type in a room number such as 42 which is incorrext as it is not in database, if you then click on "Prepare Questions" button again, you will see not message stating room is not valid.
Why is it not working and why am I getting a notice you will see on top?
Below is showing the relevant code in the correct order it is displayed in:
Javascript validation of the room textbox:
function validation() {
var isDataValid = true;
var roomTextO = document.getElementById("room");
var errRoomMsgO = document.getElementById("roomAlert");
if (roomTextO.value == "") {
errRoomMsgO.innerHTML = "Please Enter in a Room Number";
isDataValid = false;
} else if (!trimmedRoomText.length) {
errRoomMsgO.innerHTML = "Please Enter in a Room Number";
isDataValid = false;
//above is if room textbox is empty
} else if(roomTextO.getAttribute("roomthere") == false) {
errRoomMsgO.innerHTML = "This Room is Invalid";
//above is if room number in textbox does not match database, which at moment it isn't working
} else {
errRoomMsgO.innerHTML = "";
}
return isDataValid;
}
PHP code of trying to see if value in room textbox matches value in database
<?php
$username="xxx";
$password="xxx";
$database="mobile_app";
$room_there = true;
$roomresult = mysql_query( "SELECT Room FROM Room WHERE Room = " . (int) $_POST['roomChosen']);
if (isset($_POST['roomChosen'])) {
$roomresult = mysql_query( "SELECT Room FROM Room WHERE Room = " . (int) $_POST['roomChosen']);
} else {
$room_there = false;
}
if( mysql_num_rows( $roomresult ) == 0 ) $room_there = false;
?>
Below is Html of Room Textbox and submit button which is in a tag
<p><input type="text" id="room" name="roomChosen" roomthere="<?php echo $room_there; ?>" />
//message displayed if room number is in database or not
<br/><span id="roomAlert"></span></p>
// submit button
<p><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" onClick="myClickHandler()"/></p>
Finally below is the javascript handler for the submit button after it is clicked:
function myClickHandler(){
if(validation()){
showConfirm(); // this is a function for a confirmation box
}
}
Below is an edit for one of the answers below on how I am using the isset:
if ($_POST['roomChosen'] [isset()]){
$roomresult = mysql_query( "SELECT Room FROM Room WHERE Room = " . (int) $_POST['roomChosen']);
if( mysql_num_rows( $roomresult ) == 0 ) $room_there = false;
}
1) You need to check if $_POST['roomChosen'] isset() prior to attempting to use it.
2) Try:
roomTextO.getAttribute("roomthere") != 1;
First of all add isset() check for $_POST['roomChosen'].
if (isset($_POST['roomChosen']))
{
$roomresult = mysql_query( "SELECT Room FROM Room WHERE Room = " . (int) $_POST['roomChosen']);
}
else
{
$room_there = false;
}
Use php to get all the room numbers in database,
put them in a JS array.
For example:
<?php
$query = ....
while($data = mysql_fetch_array($query))
$js_var = $data.",";
?>
<script>
var str = <?=$js_var?>;
var myRooms =new Array();
myRooms = str.split(",");
</script>
Now you can use the js to check if the posted value exists in the array or not.
Related
i was ask to make an php file that would search an employees id no. and displays its results on the same page from a txt file for its records...like this....
expected output (results on the same page):
Search employee record
employee id no.: 12347 search
Result:
Lastname : Smith
Firstname : Sam
Position : Encoder
note:
if the user input is not found
expected message will be
"the id number you entered is not valid."
example sourced file: emp_record.txt
12345,Villaceran,Emelie,Instructor,20000
12346,Ayala,Jelyn,Encoder,8000
12347,Smith,Samuel,Encoder,8000
but i have been struggling putting an error note if the user input is not found... also not sure if my code structure is fit for this.... i am thinking if i should use functions for searching record and also reading and saving employees array. how can i saved the employees data into an array? i dont know if where can i insert it.....
can someone help me with this...
this is my php code..
<!DOCTYPE html>
<html>
<head>
<title>Search Employee</title>
</head>
<body>
<h1>Search Employee Record</h1>
<form method = "POST">`enter code here`
<h3>Employee ID No. :
<input type = "text" name = "id_no" >
<input type = "submit" value = "Search"></h3>
<?php
if($_POST){
$idnumber = ($_POST["id_no"]);
$empfile = fopen("emp_record.txt", "r") or die ("Unable to open file");
while (!feof($empfile)){
$employee = fgets($empfile);
$emp_record = explode(",", $employee);
$emp_id = $emp_record[0];
$emp_lastname = $emp_record[1];
$emp_firstname = $emp_record[2];
$emp_position = $emp_record[3];
$emp_salary = $emp_record[4];
if ($emp_id == $idnumber){
echo "Lastname : $emp_lastname <br> Firstname : $emp_lastname <br> Position : $emp_position <br>";
}else{
echo "The ID number you entered is NOT VALID.";
}
}
}
?>
</form>
</body>
</html>
also this is my code using functions... I know there is still missing in my code. i dont know if how can i save the record datas in an array...
<?php
$empfile = fopen("emp_record.txt", "r") or die ("Unable to open file");
function record(){
while (!feof($empfile)){
$employee = fgets($empfile);
$emp_record = explode(",", $employee);
$emp_id = $emp_record[0];
$emp_lastname = $emp_record[1];
$emp_firstname = $emp_record[2];
$emp_position = $emp_record[3];
$emp_salary = $emp_record[4];
}
//an example loop to see if what is the datas in the variables
// it only display the last line of data
for($i=0;$i<count($emp_record);$i++){
echo "$emp_id $emp_lastname $emp_firstname $emp_position ";
}
}
?>
thanks
You need to check if you have displayed the persons details and if not, then display your message after the loop has finished (so you have checked all of the records).
You can also use fgetcsv() instead of fgets() which will stop you having to do the explode() as well...
$found = false;
while ($emp_record = fgetcsv($empfile)){
$emp_id = $emp_record[0];
$emp_lastname = $emp_record[1];
$emp_firstname = $emp_record[2];
$emp_position = $emp_record[3];
$emp_salary = $emp_record[4];
if ($emp_id == $idnumber){
echo "Lastname : $emp_lastname <br> Firstname : $emp_lastname <br> Position : $emp_position <br>";
$found = true;
break; // Stop looking
}
}
if ( $found == false ) {
echo "The ID number you entered is NOT VALID.";
}
I need a help from this error i cant insert data into my database, can you see my codes, im newly in php so please help me for this. thank you for your helping and giving a good answer,
it always saying "an error eccurred while sending" it is based on my else condition
<?php
if(isset($_SESSION['username']))
{
$form = true;
$orfvp_destination = '';
$oreq_approver= '';
$oreq_noter = '';
$orfvp_duration = '';
$orfvp_purpose = '';
//to check if the form has been sent
if(isset($_POST['rfvp_destination'], $_POST['req_approver'], $_POST['req_noter'], $_POST['rfvp_duration'], $_POST['rfvp_purpose']))
{
$orfvp_destination = $_POST['rfvp_destination'];
$oreq_approver = $_POST['req_approver'];
$oreq_noter = $_POST['req_noter'];
$orfvp_duration = $_POST['rfvp_duration'];
$orfvp_purpose = $_POST['rfvp_purpose'];
//to remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$orfvp_destination = stripslashes($orfvp_destination);
$oreq_approver = stripslashes($oreq_approver);
$oreq_noter = stripslashes($oreq_noter);
$orfvp_duration = stripslashes($orfvp_duration);
$orfvp_purpose = stripslashes($orfvp_purpose);
}
//to check if all the fields are filled
if($_POST['rfvp_destination']!='' and $_POST['req_approver']!='' and $_POST['req_noter']!='' and $_POST['rfvp_duration']!='' and $_POST['rfvp_purpose']!='')
{
//to protect the variables
$rfvp_destination = mysql_real_escape_string($orfvp_destination);
$req_approver = mysql_real_escape_string($oreq_approver);
$req_noter = mysql_real_escape_string($oreq_noter);
$rfvp_duration = mysql_real_escape_string(nl2br(htmlentities($orfvp_duration, ENT_QUOTES, 'UTF-8')));
$rfvp_purpose = mysql_real_escape_string($orfvp_purpose);
//to check if the recipient exists
$dn1 = mysql_fetch_array(mysql_query('select count(user_id) as req_approver, user_id as req_approverid, (select count(*) from request) as npm from users where user_username="'.$req_approver.'"'));
$dn2 = mysql_fetch_array(mysql_query('select count(user_id) as req_noter, user_id as req_noterid, (select count(*) from request) as npm from users where user_username="'.$req_noter.'"'));
if($dn1['req_approver'] and $dn2['req_noter']==1)
{
//to check if the recipient is not the actual user
if($dn1['req_approverid']!=$_SESSION['userid'] and $dn2['req_noter']!=$_SESSION['userid'])
{
$id = $dn1['npm']+1 and $dn2['npm']+1;
//We send the message
if(mysql_query('insert into rfv (rfv_id, rfv_code, rfv_driver, rfv_vehicle)values("'.$id.'", "RFV2015-'.$id.'", "", "")')
and mysql_query('insert into rfv-p (rfv_code, rfvp_destination, rfvp_purpose, rfvp_duration)values("RFV2015-'.$id.'", "rfvp_destination", "rfvp_purpose", "rfvp_duration")')
and mysql_query('insert into request (req_code, req_date, req_status, req_dateneeded, req_requestor, req_approver, req_noter, form_id)values( "RFV2015-'.$id.'", NOW(), "Waiting for Approval", "'.$_POST['req_dateneeded'].'", "'.$_SESSION['userid'].'", "'.$dn1['req_approverid'].'","'.$dn2['req_noterid'].'", 2)'))
{
?>
<p style="color:red" align="center" >Request Successfully Created!</p>
<p style="color:red" align="center" >Home</p>
<?php
$form = false;
}
else
{
//Otherwise, we say that an error occured
$error = 'An error occurred while sending the message';
}
}
else
{
//Otherwise, we say the user cannot send a message to himself
$error = 'You cannot send a message to yourself.';
}
}
else
{
//Otherwise, we say the recipient does not exists
$error = 'The recipient does not exists.';
}
}
else
{
//Otherwise, we say a field is empty
$error = 'A field is empty. Please fill of the fields.';
}
}
elseif(isset($_GET['req_approver'], $_GET['req_noter']))
{
//We get the username for the recipient if available
$oreq_approver = $_GET['req_approver'];
$oreq_noter = $_GET['req_noter'];
}
if($form)
{
//We display a message if necessary
if(isset($error))
{
echo '<div class="message" align="center" style="color:red">'.$error.'</div>';
}
//We display the form
?>
In the above script 2 if are not closed. First one is if(isset($_SESSION['username'])) and second one is if($form). Close the curly bracket } at correct place and that should work as expected.
How do I display the error messages (you did not complete all of the required fields and this username is already taken) without going to a new page to display them (like using die instead of echo), while still not continuing the process? In other words, I don't want the user to be sent to a new page to see "you did not...," I want the error to show either below or above the on this page, but I want the error message to disallow the data from being added to the database(the next command, or a couple commands down).
//if submit is clicked
if (isset($_POST['submit'])) {
//then check if all fields are filled
if (empty($_POST['username']) | empty($_POST['password']) | empty($_POST['firstname']) | empty($_POST['MI']) | empty($_POST['lastname']) | empty($_POST['email']) | empty($_POST['phonenumber']) | empty($_POST['country']) ) {
echo('You did not complete all of the required fields. '); }
$username = $_POST['username'];
$password = $_POST['password'];
$usernamesquery = mysqli_query($connection, "SELECT * FROM users WHERE username='$username'");
if(mysqli_num_rows($usernamesquery) > 0) {
echo('This username is already taken. ');
}
} ?>
//if submit is clicked
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$usernamesquery = mysqli_query($connection, "SELECT * FROM users WHERE username='$username'");
//then check if all fields are filled
if (empty($_POST['username']) | empty($_POST['password']) | empty($_POST['firstname']) | empty($_POST['MI']) | empty($_POST['lastname']) | empty($_POST['email']) | empty($_POST['phonenumber']) | empty($_POST['country']) ) {
echo('You did not complete all of the required fields. '); }
elseif(mysqli_num_rows($usernamesquery) > 0) {
echo('This username is already taken. ');
}
else{
echo "code to submit values to database"
}
} ?>
Maybe you wanna use something like this javascript function to check for empty fields and not matching passwords (change variable names accordingly please as I took this from a little project I made):
function signup(){ //Call it on button click
var u = _("username").value;
var e = _("emailAddress").value;
var p1 = _("password").value;
var p2 = _("passwordConfirm").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Please, fill in every single field in the form...";
} else if(p1 != p2){
status.innerHTML = "The passwords do not match...";
} else if( _("terms").style.display == "none"){
status.innerHTML = "You must view our Terms & Conditions in order to proceed...";
} else { } //Redirect to a page or use Ajax to do other functions your site may need.
Notice var status = _("status");, this is where the messages will be shown on your page, you may want to add something like <span id="status"></span> to your HTML code.
Similarly to check for an available username or email on your database, you can try the following Ajax and Javascript function:
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_con.php"); //database connection file
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']); //checks the texfield doesnt have any funny unusual characters
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1"; //change table name accordingly to yours
$query = mysqli_query($db_con, $sql);
$uname_check = mysqli_num_rows($query);
//This is just some extra conditions if you wish to add
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
//This if statement will check if the username is ok to use or is taken.
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?>
//////////// Javascript function, these can be on the same php file.
function checkusername(){
var u = _("username").value;
if(u != ""){
_("usernamesats").innerHTML = 'Checking Availability...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("usernamesats").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
Notice that for you to see the warnings your username textfield must look like this: <label>Username:</label>
<input id="username" type="Text" onBlur="checkusername()" maxlength="16">
This onBlur="checkusername()" will call the JS function.
and also add somewhere after the texfield this <span id="usernamesats"></span> to display the warnings. This should all do the trick. Oh and you may want to add the Ajax file:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
somewhere in your js folder (if you have one).
Sorry if this may be a bit long and confusing but it did the work for me, I'm sure there are other ways to do it, just thought these seemed easier to understand for me.
Check this website http://www.developphp.com/list_php_video.php for more info, there are some great tutorials there to get you started with PHP and MySQL, most of this code was done following the tutorials there :) Good Luck!
(Sorry for my bad english)
Well, I've 3 errors in my code.
Error's:
First of all it's show : Notice: Undefined index: form in C:\xampp\htdocs\evantechbd\index.php on line 461. When i run this form.
if any error found it's show error message, well, but correct field is empty. Example: In this form there is 4 fields. a) upload image, b) select discussion c) subject and d) message. Suppose you upload a image, select a discussion and write a subject but forgot to write message. Then It's show "Message Required" and every filed is empty. I don't want empty field which is correct.
After successfully submitted the form it's show "Discussion was submitted ". But after that if i refresh the page it's send the data to database. But I did not click submit button. why this happen?
Here is my code:
<?php
if ($_POST['form'] == "Submit") {
$err = array();
$filed = addslashes($_FILES['file']['tmp_name']);
$img_named = addslashes($_FILES['file']['name']);
$img_type = addslashes($_FILES['file']['type']);
#$imgd = addslashes(file_get_contents($_FILES['file']['tmp_name']));
function getExtension($str)
{
$i = strrpos($str, ".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str, $i + 1, $l);
return $ext;
}
$extension = getExtension($img_named);
$extension = strtolower($extension);
$image_named_uniq = uniqid() . '.' . $extension;
$upload_path_dis = 'user/manage/discussionimg/';
$diss = $_POST['type'];
$sub = $_POST['sub'];
$msg = $_POST['msg'];
$date = "On " . date("F Y h:i:s A");
if (!isset($_SESSION['uname']))
$err[] = "You need to login";
else {
$uname = $_SESSION['uname']; //session username
if (empty($sub) && empty($msg) && empty($filed))
$err[] = "All field required";
else {
if (empty($sub))
$err[] = "Subject Requried";
if (empty($msg))
$err[] = "Message Requried";
if (empty($filed))
$err[] = "SORRY, you have to be upload a image";
}
}
if (!empty($err)) {
foreach ($err as $er) {
echo "<font color=red>$er</font><br/>";
}
}
else {
$sql = mysql_query("INSERT INTO discussion VALUES ('', '$imgd', '$image_named_uniq',
'$diss', '$sub', '$msg', '$uname', '$date' ) ");
if (!$sql)
echo "Can't submit your discussion" . mysql_error();
if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_path_dis . $image_named_uniq)) {
die('File Not Uploading');
} else {
echo "Discussion was submitted";
}
}
}
?>
Many Thanks for your help!!
Kanta.
Try changing your first if condition as follows
if (isset($_POST['submit']))
Now most of web sites uses client side validations using javascript. You can use jquery frame work to make things easier. However since you already uses validations after the POST event. You have to set values to relevant fields as bellow code. It will set tha value of the subject.
<input type="text" name="sub" value="<?php if(isset($_POST["sub"])) echo $_POST["sub"]; ?>" size="46"/>
Yes if you refresh the code it will again do the post and insert. You have to do few controls. However these things depend on your data.
a. Make unique key indexes in the database
b. Check for existing record before the insertion.
c. Redirect your page to the same page after few seconds once the user see the successful message.
I have created a form online and when the user clicks submit I want the form to check for error (ie missing field). At the moment I have the form checking the fields one by one and as soon as it encounters a error it will exit without checking the rest of the fields. Is there any way I can combine all the if statements that check for errors into one.
Here is the code
//Code to check that the Student Name field is completed
if(empty($_POST['studentName']))
{
$studentNameError = "You did not enter the student name Wank";
//echo "<h3> $studentNameError </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();
}
For example, you can make a boolean variable to mark, if there is an error, and exit if it's true + combine error messages into one
$error = false;
if(empty($_POST['studentName']))
{
$errorMessages[] = "You did not enter the student name Wank";
$error = true;
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
$errorMessages[] = "You did not select a tutor name. Please go back and select your name from the tutors list";
$error = true;
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
$errorMessages[] = "You did not select a procedure. Please go back and enter the name of the procedure which you undertook";
$error = true;
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
$errorMessages[] ="You did not select a grade. Please go back and select your grade from the drop down list";
$error = true;
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
$errorMessages[] = "The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments";
$error = true;
}
//Code to check if the tick box is checked that the tutor comment is entered
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
{
$errorMessages[] = "You must enter a reason why you have clicked the alert box";
$error = true;
}
if($error)
{
echo("<h3>".implode('<br/>',$errorMessages)."</h3>");
exit();
}
There are many ways. How about something like this, from top of my head:
$textFieldsThatCannotBeEmpty = array(
'studentName' => 'You did not enter the student name Wank',
'tutorName' => 'You did not select a tutor name. Please go back and select your name from the tutors list',
'procedure' => 'You did not select a procedure. Please go back and enter the name of the procedure which you undertook',
'grade' => 'You did not select a grade. Please go back and select your grade from the drop down list',
'studentReflection' => 'The student did not enter any comments for this procedure. Student reflection is required for each procedure. Please go back and enter any comments'
);
$errors = array();
// check text input fields
foreach($textFieldsThatCannotBeEmpty as $name => $errorMessage){
if(empty($_POST[$name])){
$errors[] = $errorMessage;
}
}
// checkbox
if(!strlen($_POST['tutorComments']) && isset($_POST['alert'])){
$errors[] = 'You must enter a reason why you have clicked the alert box';
}
if(count($errors) > 0){
// form is invalid, print errors
echo '<div class="errors">';
foreach($errors as $e){
echo '<h3>',htmlentities($e),'</h3>';
}
echo '</div>';
}else{
// form is valid, let's go and do something with the submitted data
}
Put all your error messages into an array, and loop through the $_POST. If the input field is empty, then echo the error message:
<?php
$errorMsgs = array(
'studentName' => 'You did not enter a student name',
...
);
$errors = '';
foreach($_POST as $field)
{
if(empty($field))
{
$errors .= $errorMsgs[$field] . '<br/>';
}
}
if(strlen($errors))
{
echo $errors;
exit();
}
This can be done like that (one of the many ways -- really depends on your exact requirements for validation):
<?php
$messages = array();
$errors = 0;
if (empty($_POST['studentName']))
{
$messages['studentName'] = "You did not enter the student name Wank";
$errors++;
}
if (empty($_POST['tutorName']))
{
$messages['tutorName'] = "<h3>You did not select a tutor name. Please go back and select your name from the tutors list</h3>";
$errors++;
}
if ($errors) {
// we have some invalid data in one of the fields
// display error messages (some feedback to user)
foreach ($messages as $v) {
echo $v, "\n";
}
exit();
}
// nope, we are fine
// do whatever else is required
Make a variable named $status for example and and initialize it to 0, at each test assign to it 1 if there is an error, at the end check whether if it is equal to one, exit the script otherwise continue the execution. Or better make an array and for each test assign 0 or 1, depend in the test(the field is not empty assign one else zero) and later you can echo an error message to user indicating the missing fields.