isset not givig desired result using && operator - php

if(isset($_POST["submit"])){
if (isset($_POST["name"]) && isset($_POST["roll"])){ // checking whether both text boxes are filled up
echo "$_POST[name] $_POST[roll]"; // just displays some info
}
else{ //not being executed when both text boxes are empty
header("Location:interface.php");
}
}
the above is a php code where im trying to check whether two text boxes are filled in or else i will navigate to another page. The problem is though if i fill up one text box the && condition doesn't work , it gets into the if part and echoes one value.

There is error (missing ') in:
echo "$_POST[name] $_POST[roll]";
It has to be $_POST['name'] and $_POST['roll']
UPDATE
isset() only is not enough. You should also check if it is not empty, like this:
if (!empty($_POST["name"]) && !empty($_POST["roll"])){

Related

How to go to new page on form submit only if form passes error checks?

I have an HTML form with PHP error checks. The form has several different types of fields (one for name, email, phone number, a checkbox, a drop down, etc.) and I have a PHP function written for each that runs when you hit the submit button, and checks that the form is filled in correctly and fully. If a field is left empty, or is filled in incorrectly, an error message appears. However, after I got that running, I tried to add a redirect, so that after the form is completed and submit is pressed, it brings the user to a confirmation page, if the errorchecks are passed. I wrote it like this:
if(isset($_POST['submit']) ){
header("Location:confirmed.php");}
It does what it's supposed to--bring the user to a new page--but it doesn't take into consideration any errorchecks. So, when submit is pressed, rather than run through the error checks, it immediately goes to the new page. I tried adding a variable named "errorcount" so each function so that the number of errors that occur when the form is submit will be either counted, or removed from the count, and then considered when changing the page...
if(isset($_POST['submit']) ){
if ($errorcount == 0){
header("Location:confirmed.php");}}
This didn't work either. I realized that $errorcount wasn't actually being updated at all; for what reason, I'm not sure. I set it up so each function returns $errorcount, and then called each function in the snippet of code above before running the second if statement, but it still does nothing.
I feel like I'm approaching this the wrong way, but I'm not really sure how else to do this. Please tell me if there's an easier way to achieve this, or maybe you have an idea what I'm doing wrong in the first place.
EDIT:
I am passing the variable $errorcount as global in each function, like so:
function validateName ($name, $submit){
global $errorcount;
if( empty( $submit )) {
return '';}
if (empty ($name)){
return "You didn't enter your name!";
$errorcount = $errorcount+1;
}
if (!preg_match("/^[a-zA-Z \-]*$/",$name, $matches)){
return "Please enter a valid name";
$errorcount = $errorcount+1;
}
else{
$errorcount = $errorcount-1;
}
return $errorcount;
}
However, $errorcount still does not actually change with the if loop I posted above. If I take that out (the section of code that causes the page to change) then the functions work as intended; once you click submit, the page refreshes, and error messages appear where the user did not fill out the form properly. But once all the form areas are filled out properly, clicking submit does... nothing.
EDIT 2:
I got it working. It's honestly not very efficient but it does what I need it to do. Thanks to all who helped!
You don't really need to count the errors, and you don't need to use global. Just write your validator functions so they return an error message if there is an error, or nothing if there is no error. Like this, for example:
function validateName($name) {
if (!$name) {
return 'name is required';
}
if (!preg_match("/^[a-zA-Z \-]*$/", $name)) {
return "Please enter a valid name";
}
}
Then when you run your validators, add any error messages you get to an array.
if ($error = validateName($_POST['name'] ?? '')) {
$errors['name'] = $error;
}
After you run all the validators, if the error array is empty, then there were no errors so you can redirect. And if it's not empty, then you have an array of errors keyed by field name, so you can display any errors next to the problematic fields, which your users will prefer rather than getting one error at a time in some generic location.
if (empty($errors)) {
// redirect
} else {
// stay here and show the errors
}
You're needlessly complicating things. Defining functions are only useful if you plan on re-using that code elsewhere. Try this instead:
if ( isset($_POST['submit']) )
{
if ( empty($name) )
{
echo "You didn't enter a name!";
sleep 3;
// redirect or re-load the form
}
elseif ( !preg_match("/^[a-zA-Z \-]*$/", $name, $matches) )
{
echo "Enter a valid name!";
sleep 3;
// redirect or re-load the form
}
header("Location:confirmed.php");
}

if($_POST['dropdown_value'] == null) is not also returning true if no <option> value was selected

I have Ajax posting to a php script. One of the posts is a . In the php script, I check if an option in the dropdown was selected. If not, I fill in a default value. This is then submitted to a database. See my below code for checking if an was selected:
if($_POST['dropdownValue'] == null){}
99.9% of the time, this works. I don't select an option, and the default value is returned and this is stored in my database. But now I'm finding NULL rows in my database that are filled with the value of $_POST['dropdownValue']. Should I be using the function is_null()? Or isset()? I saw another post that said to check it with $_POST['dropdownValue'] == ''. Would that be better?
you could try using the isset for this i think
if(isset($_POST['dropdownValue']) && ($_POST['dropdownValue'] != null)
{
'insert that data into my base'
}
Let's just use isset:
if( isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}

Checking multiple empty field in a form

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.');
}

alert message won't display

I got a html page with 2 forms which are using the same php script..
<?php
if ($conn) {
if (isset($_POST['form_student'])) {
if ($_POST['form_student'] == 'Send') {
if (!empty($_POST["Ime"]) && !empty($_POST["Prezime"]) && !empty($_POST["BrojIndeksa"]) && !empty($_POST["TipNastave"])) {
header('Location: forme.html');
echo "<script>alert('Processing data to sql.');</script>";
} else {
echo 'You didnt fill all fields!';
echo "<script>alert('You didn't fill all fields!');</script>";
}
}
}
if (isset($_POST['form_subject'])) {
if ($_POST['form_subject'] == 'Send') {
// same checks just like above with redirecting
// and displaying alert box
}
}
}
?>
First problem is when I don't fill all fields in, it does work and echo 'You didn't fill al fields!' but doesn't display alert box message, and it only doesn't work when I don't fill all fields. And I'm wonder how can I actually by processing php script, without redirecting to that php script page, show msg box on html page, is it possible with out ajax or jquery, or I should instead using html extension change into php, and do all checks there and avoid processing script into action=""?
That's because of the row ..
echo "alert('You didn't fill all fields!');";
Try this one instead ..
echo "alert(\"You didn't fill all fields!\");";
What you did wrong was that you had an apostrophe in the string and around the string. I don't know how to explain this but I simply made the two quotation marks to not conflict with the php echo.
Update:
Regarding the second question about the redirect and such. Could you explain it further because I don't understand a word?

Empty value clause for a string not working

I am trying to get value with ajax and the values are in form of string, but the problem is when I'm trying to use a condition of if value empty then return this or else do that
My code is
if (empty($title) || empty($thumbnail) || empty($link))
{
echo "404";
}
else
{
some custom line
}
My problem is that a 404 is returned even if the value of any one of them (title, thumbnail, or link) is not empty. Can any one point me where I am wrong?
Here's how I am getting value from ajax:
$title = mysql_real_escape_string($_REQUEST['title']);
$thumbnail = mysql_real_escape_string($_REQUEST['thumbnail']);
$link = mysql_real_escape_string($_REQUEST['link']);
First of all I suggest you to do not use empty, cause it got some specific behave.
Second: I don't get why you are using mysql_real_escape_string, you have to query a database?
Moreover i guess you (as #havelock pointed out) wanted to get a 404 if none of that values are set up.
I'm for this:
if($title && $thumbnail && $link){
//all fine..
}
else 404

Categories