i have done something like this:
<form action="validate.php" method="get">
Id :<input type="text" name="pID"/><br/><br/>
Name :<input type="text" name="pName"/><br/><br/>
Description :<input type="text" name="pDesc"/><br/><br/>
Price :<input type="text" name="pPrice"/><br/><br/>
<input type="submit" name="pSub"/>
</form>
my validate.php contains :
<?php
if (!empty($_GET['pID']) || !empty($_GET['pName']) || !empty($_GET['pDesc']) || !empty($_GET['pPrice'])){
if(is_numeric($_GET['pID']) || is_numeric($_GET['pPrice']))
{
echo "</br>Your ID :".$_GET["pID"]."</br>";
echo "Name is :".$_GET["pName"]."</br>";
echo "Description :".$_GET["pDesc"]."</br>";
echo "and Price :".$_GET["pPrice"]."</br>";
}
else{echo "Pls See That ID and Price are Numerical";}
}else{
echo "Fill up All The Values";
}
?>
is not working properly ,
1st if conditions doesn't work properly
ie. if i left blank "Name" input field message should have come saying
"Fill up All The Values "...... instead its showing the list of inputs
is there any other way to validate form (PHP)
You are using the wrong operator: || means "logical OR"; what you seem to be looking for is &&, that is "logical AND".
The code does exactly what you told it to do (see the documentation); the fact that you intended something else is not relevant to the computer:
if (!empty($_GET['pID']) || !empty($_GET['pName']) || !empty($_GET['pDesc']) || !empty($_GET['pPrice']))
means "if pID is not empty OR pName is not empty OR ..."; as soon as one or more of the fields are not empty, the condition evaluates to true.
What you can do to get what you meant:
replace OR with AND ( && )
use if (!(empty($_GET['pID']) || empty($_GET['pID'] ...)) - note that the whole expression is negated in parentheses
(read on De Morgan's laws to see why these two solutions are equivalent)
It's probably better that you switch the conditions around, like this:
if(empty($_GET['pID']) || empty($_GET['pName']) || empty($_GET['pDesc']) || empty($_GET['pPrice'])) {
echo "Please fill up all the values";
} else {
// Do other validation.
}
This way, you know your inputs are correct before you do anything else. Obviously I've not tested this, but it should work as expected. What you were saying before was asking if ANY of the inputs was not empty, do the additional validation. As one of the other commenters explained, if you wanted to do that, you should be using && rather than ||.
Changing it around just makes it a bit clearer!
It's a logic problem with your code. Using || in this situation means that if ANY of those inputs contains a value, then the first condition is met. What you want to do is AND, not OR, so that the first condition is only met if all of the inputs are !empty.
I don't remember for sure what the AND operator is for PHP, since it's been a long time, but it's probably &&.
The question already has been answered, but there is one more thing,
I recommend that you use $_POST instead of $_GET because $_POST is way more secure, as you use HTML Forms. You could look it up on internet.
Here is a link, the first answer says it all: Difference between $_POST & $_GET
This is just wrong
if (!empty($_GET['pID']) || !empty($_GET['pName']) || !empty($_GET['pDesc']) || !empty($_GET['pPrice'])){}
You need to make it like this:
if (!empty($_GET['pID'], $_GET['pName'], $_GET['pDesc'], $_GET['pPrice'])){}
And no need to make ORs at all. Also, you'd better check if any of the given values are empty and throw error on that.
Related
How can i check 2 text fields are empty with PHP.
Here is exactly what i want
there are 2 text fields in my form. I dont want the form to be submitted if both fields are empty. But if one of the text fields have a entered value form should get submitted.
I have tired this code but it wont submit if both fields values are entered.
if($_POST['inputOne'] == NULL AND $_POST['inputTwo'] == NULL )
{
die('My Error Msg.');
}
Can anyone tell me how to do this.
Thanks to Fred -ii- (with edits to he's code) i have found an answer
if(empty($_POST['inputOne']) AND empty($_POST['inputTwo']))
{
die('My Error Msg.');
}
If you dont use AND it will not look for both fields empty together instead it will look of each field separately.
if($_POST['inputOne'] == NULL OR $_POST['inputTwo'] == NULL )
"But still this look for both fields to have a value. Adding value to one field will not post the form"
Use the following then. It will check if one or both are empty.
if(empty($_POST['inputOne']) || empty($_POST['inputTwo'])){...}
instead of using == NULL
FYI: || is the same as using OR
Consult: http://php.net/manual/en/language.operators.logical.php
Or as you state in your answer: (using AND)
if(empty($_POST['inputOne']) && empty($_POST['inputTwo'])){...}
where && is the same as AND - just another quick "FYI".
It saves you a keystroke (wink)
There should be an OR instead of the AND.
if($_POST['inputOne'] == NULL OR $_POST['inputTwo'] == NULL )
{
die('My Error Msg.');
}
EDIT: If OR doesn't suffice try:
if(empty($_POST['inputOne']) || empty($_POST['inputTwo']))
{
die('My Error Msg.');
}
I'm still new in PHP and I need to know how I can create two or more conditional statements for a single elements. For instance, maybe if I had a form that I wanted to perform a certain action if some conditions were true.
I understand that one of the way is to group the statements like:
if(arg1 && arg2 && arg3) {
echo "All of these statements are true";
}
How can I separate this condition but making sure that it executes at the same time?
You can use nested if statements to accomplish the same check.
if(arg1)
{
if(arg2)
{
if(arg3)
{
echo "All of these statements are true";
}
}
}
Try this.
if(($something == 1 ) && ($someotherthing !=7) && ($something == 2)) {
echo "All of these statements are true";
}
Changed answer after what I understood of you clarification:
If you want to know if the posted form has all the required fields in PHP then you could write :
if(isset($_POST['field_name']) && $_POST['field_name'] != "")
{
//The field is set and not empty.
}
else
{
echo "Field not set...";
}
w3schools tutorial on forms :
http://www.w3schools.com/php/php_forms.asp
As for the numeric part of your question take a look at regex :
http://www.codeproject.com/Articles/9099/The-30-Minute-Regex-Tutorial
EDIT 2 : As someone mentioned if you want to know if the field is set BEFORE being sent to the server, you will need to use Javascript.
I would like to accept only small and capital letters from the user.
I tried the below code, it echoes the invalid character message but doesn't work. I mean it doesn't check. It just displays the message. Any help?
<form action="" method="post">
<input type="text" name="fname">
<input type="submit" value="Send" name="submit">
</form>
Update: this is what I have to check and insert the name to database. if numbers found in the name reject the name by displaying the error message else if the name contains only letters insert it into database. That's all I want to acheive.
<?php
if ( isset( $_POST['submit'] ) ) {
$fname = $_POST["fname"];
if(!preg_match ('/^([a-zA-Z]+)$/', $fname)){
echo "Invalid characters";
}
if (empty($fname)) {
echo '<span> First name is required</span>';
}
else{
$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("INSERT INTO test (firstname) VALUES (?)");
$stmt->bind_param("s", $fname);
$stmt->execute();
$stmt->close();
$mysqli->close();
}
}
?>
If you just want to check you could use ctype_alpha() but you said you want to ACCEPT only letters so if you choose to accept the input you could:
$fname=preg_replace('/[^a-z]/i','',$fname);
better after the check
if(!isset($_POST['fname']) || !ctype_alpha($_POST['fname'])){
// can i haz alpha letters only?
}
(reference)
There are several issues with the code, and the one you are stuck with is probably that you have the form and its processing in the same PHP file. That’s possible, but it requires a different approach. For a starter, it’s probably better to separate them.
What happens with the code posted is that the PHP processor tries to process the form data when no form has been submitted, without even checking for the presence of the data. Now $fname is undefined, so the test always fails.
The test is wrong, too. Now it only checks whether $fname contains at least one letter. For example, if(!preg_match ('/^[a-zA-Z]+$/', $fname)) would test that $fname consists of one or more Ascii letters and nothing else.
use this , this is giving me correct answer
if(!preg_match ('/^([a-zA-Z]+)$/', $fname)){
echo "Invalid characters";
}
else{
echo "correct";
}
The general idea of checking for characters that don't match the [a-zA-Z] pattern is a good one.
However, the "not" part of your if condition is in the wrong place if you want this to work. What you've got now just makes sure that any single character in fname is an upper- or lower-case Latin letter.
You want to push the "not" part of the logic into the pattern:
if (preg_match('/[^a-zA-Z]/', $fname)) {
This checks if any character in fname is not a Latin letter, which is what you're trying to do.
Edit: Your new update has a different test that also works (it appears to be from sourcecode's updated answer, but you've got several tests from the different answers here that will work equally well). But, your updated post makes it clear that your problem isn't really with the pattern for testing the name.
Your code looks like this:
if (/* invalid fname */) {
echo "Invalid characters";
}
if (/* empty fname */) {
echo '<span> First name is required</span>';
}
else {
/* insert into database */
}
That else clause only depends on the the if that comes immediately before it: the check whether fname is empty. In other words, regardless of the result of your check against the characters of fname, you insert it into the database whenever it's not empty.
One easy way to fix this is to just change your second if to an elseif. This will chain all three conditionals together, so the final else block will only occur if both of the earlier conditionals that print error messages weren't triggered.
if (/* empty fname */) {
echo 'First name is required.';
}
elseif (/* invalid fname */) {
echo 'Invalid characters';
}
else {
/* insert into database */
}
The problem:
if i submit the html form and a textbox is left blank
then i don't want it to proceed to the echo segment,
but the problem is it does proceed.
<?php
if(!isset($_POST['submit']) && empty($_POST['moon']) && empty($_POST['planet']))
{
?>
<form name="form2" method="post" action="<?php echo($_SERVER["PHP_SELF"]);?>">
<div>
Write a planet name: <input name="planet" type="text"><br>
Its moon: <input name="moon" type="text">
</div>
<div>
<input type="submit" name="submit" value="submit">
</div>
</form>
<?php
}else{
echo("Planet: ".$_POST['planet']. "<br>");
echo("Moon: ". $_POST['moon'] . "<br>");
echo "Successful.";
}
?>
As you know isset() determines if a variable is set and not null but doesn't check if it's empty.
While logic seems my if statement, I modified it from:
if(!isset($_POST['submit']) && empty($_POST['moon']) && empty($_POST['planet']))
To:
if(!isset($_POST['submit']) && ($_POST['planet']=='') && ($_POST['moon']==''))
if(!isset($_POST['submit']))
if(!isset($_POST['planet']) && !isset($_POST['moon']))
if(empty($_POST['moon']) && empty($_POST['planet']))
and none of them worked.
So am I doing something wrong with my if statement? how can I not let it proceed to the Else segment while a textbox is empty? without more if and no nested statements please.
When you submit a form, the submit button will be set, so isset($_POST['submit']) will be true, therefore !isset($_POST['submit']) will be false.
When doing an if statement with the && comparison, all conditions must be true in order to execute that block of code, otherwise it goes to the else statement.
What you need to do is actually have 2 comparison checks. Once to see if the form was never submitted and one to see if it was, and the text boxes are empty:
<?php
// Check if form was submitted
if(!isset($_POST['submit'])
{
// Display the form
}
else
{
// Form was submitted, check if values are empty
if(trim($_POST['planet'])=="" || trim($_POST['moon'])=="")
{
// One or more value is empty, do something
}
else
{
// Process form
}
}
?>
I realize you are trying to avoid nesting, but in order for the logic to flow smoothly, and the code to remain readable, this is a necessary evil.
Change
if(!isset($_POST['submit']) && empty($_POST['moon']) && empty($_POST['planet']))
To
if(!isset($_POST['submit']) || (empty($_POST['moon']) || empty($_POST['planet'])))
Then if you submit with either textbox being empty, it will redisplay the form. If both textboxes have been filled in, you will see the else part.
Your problem is that if(!isset($_POST['submit'])) is always set when the form is submitted - so that is true. You also might want to change the && to ||. By using || you say OR, so say if anyone is empty, then do this, else do that.
When I test to see if the textarea in my form is empty to do a redirect so it doesn't submit it in php, it doesn't work.
The textarea is named $_POST['message'], I know the variable exists because if I do this statement;
if (isset($_POST['message'])) {
header('Location:/');
exit();
}
Then it always redirects back to the index page so the variable must exist, although if I do this;
if (empty($_POST['message'])) {
header('Location:/');
exit();
}
It does not work, also tried with all three combos of =/==/===
if ($_POST['message'] === '') {
header('Location:/');
exit();
}
And also...
if (empty(trim($_POST['message']))) {
header('Location:/');
exit();
}
Any ideas why this is happening? And how I can prevent it, I really need to stop it as I do not want empty values in my mysql table.
I did some research and it seems some other people have had this problem, but I have seen no answer as of yet.
You probably have some whitespaces in the string, which isn't stripped by trim().
Do a strlen() on it to see what's up, and then log it byte by byte (http://stackoverflow.com/questions/591446/how-do-i-get-the-byte-values-of-a-string-in-php).
One thing you could think about is to make sure your textarea doesn't have any content in the markup (spaces, linkebreaks, whatever), like this:
<textarea></textarea>
I'm pretty sure your last try would work if you'd do it correctly, this:
if (empty(trim($_POST['message']))) {
// ...
}
...is a syntax error. empty is a language construct and does not accept expressions. Try:
$message = isset($_POST['message']) ? trim($_POST['message']) : '';
if (empty($message)) {
// $_POST['message'] is empty
}
This will ignore all input lengths below 3 chars:
if (isset($_POST['message']) && strlen(trim($_POST['message'])) < 3) {
header('Location:/');
exit();
}
However, if you just want to check, if a form was submitted, ask for the submit-button:
<input type="submit" name="submit" value="send" />
the php code would be
if (!array_key_exists('submit', $_POST)) {
header('Location:/');
exit();
}