I am currently making a self-processing form to display products that allows users to enter a quantity. I will then save the quantity in
$_POST['qty_entered']
when the users press the submit button. However, I also have an if statement to ensure that the users entered a valid quantity
if (is_numeric($_POST['qty_entered'][0]) && is_int($_POST['qty_entered'][0]) && $_POST['qty_entered'][0] > 0) {
print "'<tr><td>' test '</td>'";
}
else {
$errors = true}
Then want to print a table with the invoice on the same page, only after the submit button is pressed and if the user entered a valid quantity. However, this code is not working:
if (array_key_exists ('submit_button', $_POST)) && $errors = false{
print "Invoice";
I also have a code at the beginning of the form to set $errors to false, and if $errors is true, it will print an error message. However, it is also not working because it doesn't display the error message when I type rubbish that would trigger the if statement such as "agfasgs" or "-1"
$errors = false;
if ($errors == true) {
print "Please enter postive whole numbers for quantity <br><br>";}
Thank you for the help!
This line does not have the brackets properly inserted. Also you need == or ===(This enforces strict check) What you have currently assigns the variable. You need to check.
The === operator is supposed to compare exact content equality while the == operator would compare semantic equality
if (array_key_exists ('submit_button', $_POST)) && $errors = false{//This should have thrown an error though(FATAL)
It should be
if (array_key_exists ('submit_button', $_POST) && $errors == false){
Also, FYI, shouldnt this line
if (is_numeric($_POST['qty_entered'][0]) && is_int($_POST['qty_entered'][0]) && $_POST['qty_entered'][0] > 0) {
Be this: ?
if (is_numeric($_POST['qty_entered']) && is_int($_POST['qty_entered']) && $_POST['qty_entered'] > 0) {//access the post data properly
php
if (array_key_exists ('submit_button', $_POST)) && $errors = false{
print "Invoice";
is not valid PHP: Your parens are wrong, and you're assigning false to $errors (you want ==, not =)
if (array_key_exists('submit_button', $_POST) && $errors == false) {
Related
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 am having a problem with getting my PHP script to correctly read and execute my "IF.....ELSEIF" conditions.
In my first file, I have the following code :
if(isset($_POST['submit']) {
$selected_radio = $_POST['selection'];
$_SESSION['my_selection'] = $_POST['selection'];
if (($selected_radio == '25') {
header("url=http://xxxxxxxxxxxxxxxxx");
}
elseif (($selected_radio == '50') {
header("url=http://xxxxxxxxxxxxxxxxx");
}
}
That was the easy part.
If either "radio button" is selected, I have a Javascript function which opens a "new (child) window"
That's also easy.
But, then, comes the hard part : within that new window, the user has to select from another choice of radio buttons :
if(isset($_POST['submit']) {
$selected_radio = $_POST['my_response'];
if (($_POST['my_response'] = 'yes') && ($_SESSION['my_selection'] = '25'))
{
echo '<script type="text/javascript">window.opener.location =
"/PHP/25.php";setTimeout("window.close();", 1000);</script>';
}
elseif (($_POST['my_response'] = 'yes') && ($_SESSION['my_selection'] =
'50')) {
echo '<script type="text/javascript">window.opener.location =
"/PHP/50.php";setTimeout("window.close();", 1000);</script>';
}
Basically, this means : if the user selects "yes" in the current (child) window, then the window closes, and the parent window re-directs to "25.php" or "50.php"..........depending on the value of the $_SESSION['my_selection'] --- which was selected earlier in the parent-window
But, for some reason, it's not working. My code is executing only the FIRST IF-condition :
if (($_POST['my_response'] = 'yes') && ($_SESSION['my_selection'] = '25'))
{
echo '<script type="text/javascript">window.opener.location =
"/PHP/25.php";setTimeout("window.close();", 1000);</script>';
}
It is completely ignoring the second one.............even if the user had earlier selected "50" in the parent-window.
My first thought was : the SESSION value of the radio-button ---- $_SESSION['my_selection'] --- was not being carried-over into the new (child) window.
But, I used "echo" to verify that this was working properly. The value was indeed being carried-over into the new (child) window.
However, after the child-window closes, and the parent-window is re-directed, I used "echo" again to track any errors........and it showed that : the value of $_SESSION['my_selection'] is always equal to "25" !
In a nutshell : why is the second IF-statement being ignored??
elseif (($_POST['my_response'] = 'yes') && ($_SESSION['my_selection'] =
'50')) {
echo '<script type="text/javascript">window.opener.location =
"/PHP/50.php";setTimeout("window.close();", 1000);</script>';
($_POST['my_response'] = 'yes') && ($_SESSION['my_selection'] = '25')
^ ^
A single equals sign is an assignment and as the value you are assigning is truthy the if will always evaluate to true. Use == for a comparison.
You are using = instead of == in nearly all statements:
if (($_POST['my_response'] = 'yes')
should be
if (($_POST['my_response'] == 'yes')
This way, you don't check if $_POST['my_response'] is equal to "yes", but if it is possible to assign "yes" to $_POST['my_response']. As a result, all your if statements are true.
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 a conditional if check on a webform on which ajax (and php) is doing the submit work.
if(empty($name) or empty($message))
{
do something
}
The above is working if one of the 2 strings is empty.I want to add to the above
or (empty($name) and empty($message))
for checking if both strings are empty but in someway its not working!I want to make sure all 3 senarios are covered,Name empty or Message empty or both empty.
Any ideas?
This will check that both $name and $message is not blank, than true
if($name != '' && $message != '') {
//Do something
}
If you use this, this will check if any 1 field is empty than the condition is true
if($name == '' || $message == '') {
//Do something
}
If you use this, this will be true if both are empty
if($name == '' && $message == '') {
//Do something
}
Replace "or" with "||". Example:
if (empty($name) || empty($message))
{
// Do something
}
or means "If either condition is true", not "If exactly one condition is true".
The code you have already covers your requirement.
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.