I am learning how to code PHP and I have two pages: rates.html and rates.php. Our assignment has it so that we only need to run rates.php and will no longer need to use rates.html. My way of going around this problem is as follows:
if (empty($_POST['txtInput'])){
$inputCurrency = 0;
$outputCurrency = 0;
$txtInput = '';
} else {
$inputCurrency = $_POST['inputCurrency'];
$outputCurrency = $_POST['outputCurrency'];
$txtInput = $_POST['txtInput'];
}
Input and output currencies are made in the form of a drop down list, and txtInput is the number that the user wants to convert.
The only problem with this is that my page throws up an error message when a user submits a form without any input in the field. The page loads the following code:
if ( empty($txtInput) ) {
$error_message = 'Input is a required field.'; }
else if ( !is_numeric($txtInput) ) {
$error_message = 'Input must be a valid number.'; }
else if ( $txtInput <= 0 ) {
$error_message = 'Input must be greater than zero.'; }
else {
$error_message = ''; }
Is there a way for the flag to not be thrown up on the pages first load? Any help would be appreciated
Wrap your logic that should only run when a form is submitted in an if block that checks to see if the form is submitted via POST:
if ('POST' === $_SERVER['REQUEST_METHOD']) {
// Form submitted. Put form logic here.
}
Related
I have a simple registration form on my site. There are various validation rules regarding empty fields, incorrect characters etc.
I have a variable called $error, which is initally set to 0 but if there is a validation error it sets to 1 and another variable $error_message displays the error message itself. Below is an example:
if (strlen($firstName) == 0) {
$error = 1;
$error_message = "<br/> First name is required";
}
if (!preg_match($expName, $firstName)) {
$error = 1;
$error_message = 'The First Name you entered does not appear to be valid.<br />';
}
if (strlen($lastName) == 0) {
$error = 1;
$error_message = "<br/>Last name is required";
}
if (!preg_match($expName, $lastName)) {
$error = 1;
$error_message = 'The Last Name you entered does not appear to be valid.<br />';
}
Whenever there is an error, the registration fails and the user is notified of what error it is, no last name, incorrect characters on first name, etc etc.
The problem that I have is that only one error message displays, even if the user has had multiple validation errors in their form.
My specific question is: How do I display multiple error messages, if there are indeed multiple error messages?
I have thought about setting $error = ()array; and using a while loop to possibly loop through and display each error message but I am unsure if I can keep the 0 and 1 for error flagging, if that makes sense.
Is this possible?
I have looked through a few answers on this topic but they seem to relate to displaying multiple rows from a database, which I am not doing on this particular page.
Below is the container/column which the error message should be displayed (PHP generated).
<div class='icon-center-check-circle'>
<i class='fas fa-times-circle'></i>
</div>
<div class='col-md-succ'>
<br>Error with registration:</br>
<br>$error_message</br>
<br><a href = 'register.php' <button type = 'Submit' name = 'Submit'>Try Again</button></a></br>
</div>
</div>
</div>
Thanks for your time and any advice you can share!
Store your errors in the $error_message array then simply use empty to test whether or not there are any errors. No need to set a separate flag.
$error_message[] = 'Last name is required';
Then, to display them:
<?php
if (!empty($error_message)) {
echo '<br>Error with registration:</br>';
foreach ($error_message as $error) {
echo '<br>' . $error . '</br>';
}
}
?>
just a small example:
<?php
$errors = [];
$someVar = '';
if (empty($someVar)) {
$errors[] = 'need input';
}
if (!false) {
$errors[] = 'another error';
}
$errorsOccured = count($errors) > 0;
foreach ($errors as $error) {
echo $error . PHP_EOL;
}
If you use an array, you can check at the end if errors occured. (if there were no errors, the array would be empty.)
The running code can be found here:
I've got the following line of code in PHP at the top of the page making sure all form fields have content in them and not submitted empty...
if(!isset($_POST['name'])) { $err_name = 1; }
if (!isset($_POST['phone'])) { $err_phone = 1; }
if (!isset($_POST['email'])) { $err_email = 1; }
if ((!isset($_POST['serve'])) && ($_POST['other'] == "")) { $err_serve = 1; }
name is a text input
email is a text input
phone is a text input
serve is a checkbox array
other is a text input
Then below that I've got the following lines which allow the php code to continue if there are no errors (above)
if (($err_name != 1) && ($err_phone != 1) && ($err_email != 1) && ($err_serve != 1)) {
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // required
$serve = $_POST['serve'];
$other = $_POST['other'];
Then I've got this next to each form field...
<?php if ($err_name == 1) { echo '<font color="red">Name cannot be empty</font>'; } ?>
<?php if ($err_phone == 1) { echo '<br /><font color="red">Phone cannot be empty</font>'; } ?>
<?php if ($err_email == 1) { echo '<font color="red">Email cannot be empty</font>'; } ?>
<?php if($err_serve == 1) { echo '<br /><font color="red">You must choose at least 1 area to serve</font>'; } ?>
Can someone please help me figure out WHY its doing the following...
if I take && ($err_serve != 1) out of the 2nd code, everything
except phone shows error messages
if I leave it in, ONLY err_serve throws error. The others are
ignored and no error is displayed.
Phone refuses to throw error messages. This is everything where $_POST
handling is in the php.
Note that all tests are done by submitting a completely empty form
The values will be set whether or not they are filled with a value. If it's an empty value, it's still a value.
Instead of using isset(), use empty(). It checks both if:
The value exists at all
The value is something other than 0, an empty string, false, etc.
The reason it works for the checkbox, is because when a checkbox is not checked, the browser does not send the value at all. This is contrary to text fields. A browser will send the value of a text field whether or not it's empty.
http://ca2.php.net/manual/en/function.empty.php
I'm trying to create a dynamic if-statement. The reason I want to do this, is because I need to check server-sided whether inputfields match my regex and are not empty. However, some of my inputfields can be removed in my CMS, meaning there would be more/less inputfields accordingly.
Ideally I would add variables in my if-statement but I'm not 100% sure if that's allowed, so perhaps I would need an other way to solve this problem. Here's what I tried:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = " || $_POST['streetname'] == ''"; //Used to check if field is empty
$pstreetname = " || !preg_match($streetnameReg,$_POST['streetname'])"; //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = ''; //Not needed in check
$pstreetname = ''; //Also not needed in check
}
// more of these if/else statements
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' $cstreetname $cpostalcode $chometown $ctelnr $csex $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
else
{
//Regex check, after that more code
}
My idea was to check if a specific field is shown on the front-end and in that case I'm creating some variables that I want to paste in my if-statements.
I'm getting an error saying Server error meaning my php-code would be invalid.
Is it even possible at all to make a dynamic if-statement? If yes, at what part am I failing?
Help is much appreciated! Thanks in advance.
First of all, since it looks like you need to combine all of the conditionals with ||, you can correct your program by writing it like this:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = $_POST['streetname'] == ''; //Used to check if field is empty
$pstreetname = !preg_match($streetnameReg,$_POST['streetname']); //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = false; //Not needed in check
$pstreetname = false; //Also not needed in check
}
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' || $cstreetname || $cpostalcode || $chometown || $ctelnr || $csex || $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
This would work, but it's unwieldy. A much better solution would be to use an array (let's name it $errors that gets dynamically populated with errors resulting from validating your fields. Like this:
$errors = array();
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
if ($streetname == '') {
$errors[] = 'Streetname cannot be empty.'; // message is optional
}
if (!preg_match($streetnameReg,$streetname)) {
$errors[] = 'Streetname is invalid.'; // message is optional
}
}
And then:
if ($errors) {
echo 'There are errors with the data you submitted.';
header('refresh:3;url=index.php');
}
If you provided human-readable error messages you can also arrange for them to be displayed so that the user knows what they need to fix. And of course there are lots of variations of this technique you can use -- e.g. group the error messages by field so that you only show one error for each field.
If you want to check for empty $_POST fields you can do something like this
$error = False;
foreach($_POST as $k => $v)
{
if(empty($v))
{
$error .= "Field " . $k . " is empty\n";
}
}
if(!$error)
{
echo "We don't have any errrors, proceed with code";
}
else
{
echo "Ops we have empty fields.\n";
echo $error;
}
And after you are sure that all the fields are not empty you can do other stuff.
I have 2 textboxes one is for maximum marks and the other for the obtained marks..
The value to be entered in the second box must be restricted in such a way that it is less than or equal to the maximum marks.. Only numbers must be entered into those boxes..
Maximum Marks<input type=text name=maxmarks maxlength='2' >
Obtained marks<input type='text' maxlength='2' name='obtmarks'>
Please help me with this.. Thank you in advance..
Well if you want to do it client side, you will have to use Javascript. If you want to do it server-side, why don't you send them back the page with an error message if the second number exceeds the first. You might also might want to look into HTML5 input options if that is an available option for you. Those will automatically do the number validation.
You could try something like this...
$response_array = array();
if($obtained > $max){
$response_array['status'] = 'error';
$response_array['message'] = '<div class="alert alert-error">Obtained to big</div>';
}
if(!is_numeric($obtained){
$response_array['status'] = 'error';
$response_array['message'] = '<div class="alert alert-error">Obtained not a number</div>';
}
echo json_encode($response_array);
This is pseudo code, obviously you will need to tweak it for your purpose.
First you have to make checks in your php script that you submit the form, you can use javascript after to make it more user friendly but if someone change the source code or just turn javascript off he will be able to submit anyting.
In your process_form.php:
session_start();
$errors = array();
if (!isset($_POST['maxmarks']) || empty($_POST['maxmarks'])) {
$errors[] = 'The Maximum Marks field is required.';
}
else {
if (!is_int($_POST['maxmarks'])) {
$errors[] = 'The Maximum Marks field must be an integer.';
}
else {
$maxmarks= (int) trim($_POST['maxmarks']);
}
}
if (!isset($_POST['obtmarks']) || empty($_POST['obtmarks'])) {
$errors[] = 'The Obtained Marks field is required.';
}
else {
if (!is_int($_POST['obtmarks'])) {
$errors[] = 'The Obtained Marks field must be an integer.';
}
else {
$obtmarks= (int) trim($_POST['obtmarks']);
}
}
if (!empty($errors)) {
$_SESSION['form_errors'] = $errors;
header('Location: your_form.php');
die();
}
else if ($obtmarks > $maxmarks){
$errors[] = 'The Obtained Marks must be less or equal to Maximum Marks.';
$_SESSION['form_errors'] = $errors;
header('Location: your_form.php');
die();
}
else {
//process data
}
In your_form.php now:
session_start();
if (isset($_SESSION['form_errors']) && !empty($_SESSION['form_errors'])) {
$errors = $_SESSION['form_errors'];
unset($_SESSION['form_errors']);
}
echo '<ul>';
if (isset($errors)) {
foreach($errors as $error) {
echo '<li>' . $error . '</li>';
}
}
echo '</ul>';
//your form here
I've a form,in the form only few fields are mandatory.When a fields is not mandatory,it should not check for empty data validation.If the non mandatory field contain data then it shoudl check the data,validation should happen only when data present.
My below code check for all fields.For eg:Say phone is not mandatory in below code,how to change the code.
$validate = array(
array($x, '/^[a-z\d ]{4,20}$/i', "Please enter valid name."),
array($y, '/^[a-z\d ]{4,20}$/i', "Please enter a real category."),
array($phone, '/^\(?[0-9]{3}\)?|[0-9]{3}[-. ]? [0-9]{3}[-. ]?[0-9]{4}$/' , "Please enter a valid phone number")
);
$error = '';
foreach ($validate as $validation)
{
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
if($error != '')
{
echo $error;
exit;
}
Comment on this post,if it is not clear.
Thanks in advance!
If you want to check if at least required fields have been submitted, you can check whether they have been set and have a truthy value using the isset and empty functions.
For example:
if ( isset($_POST['username'], $_POST['password']) &&
! empty($_POST['username']) && ! empty($_POST['password']) ) {
// validation here
}
That would check if the username and password fields were submitted and have a value, whereas for example an email field wouldn't necessarily have been filled in for the above condition to return true.
If you know the mandatory fields before hand I'll suggest you group them in an array and test for based on the current key. If a key is in not mandatory but holds value you can test otherwise do your regular check.
$error = '';
$mandatoryFields = array('key1', 'key2' 'key3');
foreach ($validate as $validation)
{
if (!in_array($validation[0], $mandatoryFields) && strlen(trim($validation[0])) > 0)
{
// There is data in a non mandatory field.
// Perform your test.
}
else {
// Do your regular test.
if (!preg_match($validation[1],$validation[0]))
{
$error .= $validation[2];
}
}
}
You can give this a try.