I'm working on a final project for a PHP class and I'm having trouble with validating the code. In the else if part of the code I always get an error at both of these else if statements and the application stops processing.
The code below is a part of a .php file that has a HTML form for setting reminders.
} else if (!checkdate($_POST['reminderMonth'],$_POST['reminderDate'],$_POST['remindereEar'])) {
$error_message = "Selected date does not exist.";
} else if ($reminderDate <= $t_date) {
$error_message = "Selected date has already occured.";
All of the code:
if(isset($_POST['submit'])) {
//get data
$t_date = date(Ymd);
$year = $_POST['reminderYear'];
$month = $_POST['reminderMonth'];
$day = $_POST['reminderDay'];
//validate data
$reminderDate = $year.$month.$day;
if (empty($_POST['reminderName'])) {
$error_message = "Name is a required field.";
} else if (!checkdate($_POST['reminderMonth'],$_POST['reminderDate'],$_POST['remindereEar'])) {
$error_message = "Selected date does not exist.";
} else if ($reminderDate <= $t_date) {
$error_message = "Selected date has already occured.";
} else {
$error_message = ''; }
//redirect
if(empty($error_message)) {
mysql_query("INSERT INTO reminder_event
(reminderName,reminderDescript,reminderDate)
VALUES
('{$reminderName}','{$reminderDescript}','{$reminderDate}')");
header("Refresh: 1;url=reminder_list.php");
} else {
echo($error_message); } }
date(Ymd) will produce error should be
date('Y m d');
and make sure $reminderDate = $year.$month.$day; is formatted in the same way
$reminderDate = $year.' '.$month.' '.$day;
Also 2 typos:
$_POST['reminderDate'],$_POST['remindereEar']
Dont know if this is a solution, but still looks like it will cause problems if you run it your way
I see 2 typos:
$_POST['reminderDate'],$_POST['remindereEar']
It should be:
$_POST['reminderDay'],$_POST['reminderYear']
You made a mistake with reminderDate and remindereEar.
It should be instead : $_POST['reminderDay'], $_POST['reminderYear']
Tell me if you get more error after changing that.
Related
I am checking data if its not exist than insert. so i am using if else condition.
take a glance on code.
if($_POST['save_appointment']){
if(is_user_logged_in()){
$user_appontment_sql = "select * from ".$wpdb->prefix."table where status=1 AND event_id=1 AND user_id=2";
$get_user_data_row = $wpdb->get_row($user_appontment_sql);
if(isset($get_user_data_row)){
echo '<div class="saved_thing">'.__('You have already filled form for appointment for this date').'</div>';
}
else{
$push_form_data=array();
if($_POST['username']){
$user_data=array('username'=>$_POST['username'],'usernamelabel'=>$_POST['usernamelabel']);
$user_name=array('name_data'=>$user_data);
array_push($push_form_data,$user_name);
}
$form_data_all=json_encode($push_form_data);
$done = add_appointment($_POST,$form_data_all);
if($done==true)
{
echo '<div class="saved_thing">'.__('Mange tak. Du hører fra os snarest !').'</div>';
$user_status_mail = "select * from ".$wpdb->prefix."volunteer_app_setting where meta_key='admin_email' OR meta_key='email_send_status' OR meta_key='email_template_accept'";
$get_appointment_send_mail = $wpdb->get_results($user_status_mail);
$event_metadata=unserialize($event_datas_count[0]->pstdata_value);
if($event_metadata['notification_mail']=='1')
{
require_once(dirname(dirname(dirname(dirname(__FILE__))))."/volunteer-appointment/mail/send_mail.php");
$selected_template=$event_meta_data['mail_temp_form_submission'];
$from=$get_appointment_send_mail[0]->meta_value;
$data=array('first_name'=>$_POST['username'],'send_to_admin'=>1,'event_date'=>get_post_meta($_POST['event_id'],'event-date',true),'event_name'=>get_the_title());
$current_user = wp_get_current_user();
$send_mail=mail_user($current_user->user_email,$selected_template,$from,$data);
if($send_mail){
echo '<div class="saved_thing">'.__('E-mail notifikation afsendt til administrator').'</div>';
}
else{
//echo "<script>alert('Mail not send');</script>";
}
}
}
else
{
echo '<div class="saved_thing">'.__('Fejl!!!').'</div>';
}
//}
return;
}
}
}
first we check the data, if its not exist than go to else part.
its is going in if part all the time even data is not exists but saving data . In else part add_appointment() is the issue. this function is saving the data.
I debug
code is checking the condition and if data is not exist in database than go to else part, save data using the function add_appointment() and after executaion of the function again its going to else condition and showing message You have already filled form for appointment for this date
Change your if condition to
from -> if(isset($get_user_data_row))
to -> if(!empty($get_user_data_row))
If no rows are found, it will return 0
if($get_user_data_row > 0) {
// Some code here
} else {
// Some functions here
}
I have small problem with date validation. It works if it only validates a day, not the whole date.
If, today is 21.07.2015, validation enables dates before the 21st of each month/each year. It should accept only dates starting from today.
Code is here:
if (empty ($_POST['data'])) {
$data_error = "You need to type a date";
++$error_counter;
} elseif ($_POST['data'] < date("d.m.Y")) {
$data_error = "You have chosen incorrect date";
++$error_counter;
} else {
$data = $_POST['data'];
}
You can compare by strtotime()
if (empty ($_POST['data'])) {
$data_error = "You need to type a date";
++$error_counter;
} elseif (strtotime($_POST['data']) < strtotime(date("d.m.Y"))) {
$data_error = "You have chosen incorrect date";
++$error_counter;
} else {
$data = $_POST['data'];
}
My form has Phone and Email fields.
Many people might not be wanting/able to put both,
so I thought, that the validator would require only
one of those two filled, instead of requiring the both filled.
I've tried thinking of different ways to do it but I'm pretty new to PHP,
so I couldn't come with any.
Would this be possible?
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["phone"]))
{$phone = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
}
Thank you.
As your title states, 1 / 2 form fields is filled in.
$i = 0; // PUT THIS BEFORE YOUR IF STATEMENTS
Inside of your statements:
if (empty($_POST["phone"])) {
$phone = "";
} else {
$i++; // PUT THIS IN ALL YOU WANT TO COUNT, IT WILL ADD 1 to $i EACH TIME YOU CALL IT
$website = test_input($_POST["website"]);
}
Now at the end, if
// YOU NEED TO CHANGE YOUR NUMBERS TO WHATEVER COUNT YOU WANT
if ($i < 2) { // IF $i IS LESS THAN 2
// YOUR CODE HERE
} else { // IF $i IS 2 OR MORE
// YOUR CODE HERE
}
Hope this is somewhat useful!
or as stated above, you can use an
if (#$A && #$B) { // REQUIRES BOTH TO BE TRUE
// YOUR CODE HERE
} elseif (#$A || #$B) { // REQUIRES ONLY ONE TO BE TRUE
// YOUR CODE HERE
} else { // NONE ARE TRUE
// YOUR CODE HERE
}
if you are wondering about the # signs above, they are simply checking if they are set, you could change the code to !empty($A) which is what you used above. Putting the ! before the empty function checks that it is false or that $A is actually set.
If i would have to check a form like you, i'd do it this way:
$res = '';
if(empty($_POST['name']))
$res .= 'The name is required.<br>';
if(empty($_POST['email']))
$res .= 'The email is required.<br>';
if(empty($_POST['phone']) && empty($_POST['email']))
$res .= 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo 'We have these errors:';
echo $res;
}
else {
echo 'No Errors!';
}
If you want to show only one error each time, use this code:
$res = '';
if(empty($_POST['name']))
$res = 'The name is required.<br>';
elseif(empty($_POST['email']))
$res = 'The email is required.<br>';
elseif(empty($_POST['phone']) && empty($_POST['email']))
$res = 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo $res;
}
else {
echo 'No Error!';
}
Even if i think it's very basic, i'll explain the mentioned part, even if you could look it up from php.net:
$res .= 'The name is required';
The ".=" operator adds the part 'The name is required' to the variable $res. If this happens the first time, the variable will be empty, because i initialized it as an empty string. With every ongoing line, another error Message will be added to the string.
if(strlen($res) > 0) {
strlen() will return the length of the string in $res. If no error occured, it would still be empty, so strlen() would return 0.
Okay, everything I've checked on this site referring to validation isn't what I'm looking for.
What I'm looking to do is a minimum length and maximum length of a value in firstname and secondname, this is the code which I currently have.
if (isset($_POST['submit'])) {
$errors = array();
if (isset($_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "You have not entered a first name";
}
if (isset($_POST['secondname'])) {
$sn = $_POST['secondname'];
} else {
$errors[] = "You have not entered a second name";
}
I was just wondering how would I apply preg_match to those which the minimum is 4 letters and the maximum is 15?
I do know it's something to do with
if(preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname']))
In doing this I tried to do
if (isset($_POST['firstname']) && preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname')) {
But that also gave me an error :/
Could anyone give me a solution for this?
Thanks!
UPDATE:-
Nvm, I found a way around it. I just did this
if (isset($_POST['firstname'])) {
if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "<center> <h3> You must enter between 4 and 15 characters! </h3></center>";
}
} else {
$errors[] = "You have not entered a name";
}
For both the firstname and secondname. :)
Why don't you just use strlen() to get the string length, and then test it against your limits ?
$length = strlen($nick);
if ($length > 3 AND $length < 16) {
//Do STuff
} else {
//Do stuff for failed requirement
}
I found a way around it. I just did this
if (isset($_POST['firstname'])) {
if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "<center> <h3>You must enter between 4 and 15 characters!</h3> </center>";
}
} else {
$errors[] = "You have not entered a name";
}
For both the firstname and secondname.
I know this is embarrassing easy but I cannot get this to work right now, keep getting syntax errors, I just added in a jquery code that pre-fills in a form filed and when you select the form field it will clear the default value. The result though is if a user submits the form without changing the default value, I need to see if it exist in addition to my normal string sanitations
In this snippet below of PHP I need to run 2 conditions on $fname but below will not work, can someone help please
$fname = 'first name';
if (trim($fname) == '') && ($fname != 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
For karim79
this code below from your example, exactly like this gives me this error
Fatal Error: Can't use function return value in write context on line 5
<?PHP
$fname = '';
if(empty(trim($fname))) {
echo "First name is empty";
}
?>
$fname = 'first name';
if (trim($fname) == '' || $fname != 'first name') {
$err .= "error";
} else {
$err .= "all good";
}
I would prefer to use strcmp:
if (trim($fname) == '' || strcmp($fname,'first name') !== 0) {
$err .= "error";
} else {
$err .= "all good";
}
If the case of the first name is not important, you should consider using strcasecmp instead. Also note you can use empty to test for the empty string:
$fname = '';
$fname = trim($fname);
if(empty($fname)) {
echo "First name is empty";
} else {
echo "Not empty";
}
When using empty, beware the following (from the manual):
Note: empty() only checks variables as
anything else will result in a parse
error. In other words, the following
will not work: empty(trim($name)).
$fname = 'first name';
if (trim($fname) == '' || $fname == 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
PS: I assumed you want to raise an error if the string is either empty or the standard value. If that's wrong let me know.
I would NOT recommend using empty() for anything. It has some tricky return patterns, including telling you that a 0 is empty, and things of that nature. This, unfortunately, is a shortcoming of PHP.
Instead, try this algorithm (The following assumes your form POSTs):
<?php
$err = array();
// this is for sticklers..with E_STRICT on, PHP
// complains about uninitialized indexes
if( isset($_POST['name']) )
{
$name = trim($_POST['name']);
}
else
{
$name = '';
}
if( strlen($name) == 0 )
{
$err[] = "First name is required.";
}
// after validation is complete....
if( count($err) > 0 )
{
echo "There are errors!";
// probably something more elaborate here, like
// outputting an ordered list to display each error
print_r($err);
}
else
{
echo "It's all good!";
}
?>