Creating an index for an HTML form in PHP using $_POST

Here is the PHP code snippet I am working with:

<?php
    if(isset($_POST['address_building_number']) OR !isset($_POST['address_building_number'])){
        $address_building_number = $_POST['address_building_number'];
        echo 'Hello';
        $good = 'Good bye';
    }
    echo $address_building_number;
    echo $good;

?>

After hitting the submit button, the words "Hello" and "Good bye" are displayed, but I am receiving a PHP Notice: Undefined index: message. The variable

$_POST['address_building_number']
is populated from an HTML input form with the name 'address_building_number'.

I need to adjust the line

if(isset($_POST['address_building_number']) OR !isset($_POST['address_building_number'])){
in a way that defines the index while still being able to display "Hello" and "Good bye". How can I achieve this?

Answer №1

Edit

All-in-one version

<?php
    if(isset($_POST['address_building_number']) || !empty($_POST['address_building_number'])){
        $address_building_number = $_POST['address_building_number'];
        echo 'Greetings';
        $farewell = 'Farewell';
    }
    echo $address_building_number;
    echo $farewell;

    // comment out exit; if you want the form to NOT appear after submit
    // exit;
?>

<form action="" method="post">
   Name: <input type="text" name="address_building_number"><br>
   <input type="submit" value="Submit">
</form>

Original answer

Your conditionals appear to contradict each other.

Observe the if(isset and if(!isset for the

$_POST['address_building_number']

The issue here is, "if it IS set and if it is NOT set"; creating a conflicting statement.

You likely intended to use:

if(isset($_POST['address_building_number']) OR !empty($_POST['address_building_number'])) 

(Just an FYI) If that's correct, || takes precedence over OR, so use:

if(isset($_POST['address_building_number']) || !empty($_POST['address_building_number']))

...which checks if it is set or not empty.

The following has been tested successfully and everything echoed without errors:

HTML

<form action="action.php" method="post">
   Name: <input type="text" name="address_building_number"><br>
   <input type="submit" value="Submit">
</form>

PHP (action.php) as an example

<?php
    if(isset($_POST['address_building_number']) || !empty($_POST['address_building_number'])){
        $address_building_number = $_POST['address_building_number'];
        echo 'Greetings';
        $farewell = 'Farewell';
    }
    echo $address_building_number;
    echo $farewell;
?>

Regarding the request to "define the index while still being able to echo Greetings and Farewell" - The intent behind this is unclear.

If by that you mean, "if you can still echo "Greetings and Farewell" outside of that conditional statement", then the response is affirmative; aligning with what my answer accomplishes, using the OR (||) operator. Had it been the AND (&&) operator, this wouldn't be feasible.

Answer №2

First, your if statement is incorrect as it always evaluates to true. It's unclear what you are attempting to achieve here.

Secondly, the PHP Notice: Undefined index appears because your if statement is always evaluating to true regardless of whether the form has been submitted or not.

Thirdly, consider changing the if statement to:

if(isset($_POST['submit'])) {

Also ensure that the submit button has name="submit"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery AJAX to Redirect to a 404 Page in Case the Load Method Encounters Failure

My website utilizes AJAX to load all pages using the jQuery load method. I modified this tutorial to work with Wordpress. The issue I am facing now is that when the load method encounters an error (such as a 404 due to a broken link), the AJAX transition ...

Issue with displaying the Bootstrap paginator stylingSomething seems to be

Currently, I am working on a PHP project that involves creating a table with Bootstrap styling. To achieve this, I referred to a tutorial which guided me through the process. After linking the necessary Bootstrap CSS file using the provided code snippet, ...

Resolving the 500 Error in PHP when retrieving the latest insert ID using Doctrine

I recently migrated a web module from PHP 5.3 to PHP 7.2 and also started using doctrine. Initially, everything was working perfectly fine. However, the web module suddenly started displaying random 500 errors, even on different actions. I have been unable ...

Accessing content from a text file and showcasing a designated line

Apologies if my wording was unclear... In this scenario, we will refer to the text file as example.txt. The value in question will be labeled as "Apple" My goal is to retrieve example.txt, search for Apple within it, and display the entire line where thi ...

Incorrect order shown by echoing in PHP MySQL while loop with if condition

I am currently working on a task involving echoing a list from MySQL using a while loop. However, the list appears to be in the wrong order when viewing it here on . Why is this happening? The purpose of the if statements is to ensure that the top and bot ...

Looking to eliminate the usage of hostname, username, and password in PHP code

Here is some PHP code I need help with: <?php /* $host='127.0.0.1'; $uname='root'; $pwd='password'; $db="android"; */ require_once('dbConnect.php'); /* $con = mysql_connect($host,$uname,$pwd) or die("connect ...

Using jQuery to serialize parameters for AJAX requests

I could use some help figuring out how to set up parameters for a $.ajax submission. Currently, I have multiple pairs of HTML inputs (i pairs): > <input type="hidden" value="31" name="product_id"> <input > type="hidden" value="3" name="qua ...

Should I implement this practice when developing an AJAX website? Is it recommended to enable PHP code within .html files, or should I switch to using .php files instead?

Query: I am interested in executing PHP within HTML documents to include HTML using PHP include();. Question: Would it be more beneficial to change .php to .txt for my AJAX-loaded pages and switch my .html files to .php? This approach might resolve the ...

Could it be a mistake causing Echo to fail in fetching information from advanced custom fields?

When setting up in-content advertising for my blog posts on WordPress, I wanted the ads to point towards other sections of my site. Everything was working fine with the shortcode [in-content] pulling the most recent post from the 'advertising' cu ...

PHP version 7.2.1 is throwing an error indicating an undefined index for the file_upload

Encountering an error message: Notice: Undefined index: file_upload in C:\MAMP\htdocs\basic_files\upload.php on line 3 Each time I attempt to upload a file using the form. While many attribute this issue to problems with enctype or ...

PHP function with JSON response encountered an error during the AJAX call

I am currently working on creating a News Ticker that utilizes PHP, Javascript, and AJAX. The first step involved creating a PHP function called getFeed(), which gathers data from various news websites into an Array. This data is then returned in JSON form ...

Troubleshooting Issues with Loading Styles and JavaScript for Wordpress Plugin in Admin Area

Can someone please help me with troubleshooting my stylesheet and scripts that are not working properly? I have included styles in the stylesheet and an alert in my script file, but for some reason they are not functioning as expected. (I have confirmed ...

Creating PDFs in PHP with support for A3, A4, and A5 sizes

I am exploring the possibility of using PHP to generate PDFs for different document sizes such as A3, A4, and A5. Currently, I have a container with multiple nested divs that are absolutely positioned within it. My goal is to have this container set at a ...

Querying data from a MYSQL database using the SELECT and WHERE

Can someone help me retrieve the content of a single cell in my table using this code? session_start(); $username = $_SESSION["username"]; // Establish database connection mysql_connect("localhost", "root", "*!#@%#") or die(mysql_error()); // Select Dat ...

Utilizing a PHP-scripted multidimensional array in an AJAX success function

I've encountered an issue while trying to access a multidimensional array passed to my AJAX success function. Here's how I'm sending the data: $response = array(); $response['message']['name'] = $name; $response['m ...

A guide on utilizing the editUrl property in jQgrid with jQuery

Trying to implement dynamic edit/add of rows in jqgrid but facing issue with the editUrl attribute. Can someone please advise on: 1) Should the php file be kept in the server or within our application? 2) Currently using editurl: './data_save.php&ap ...

SQLSTATE[42000]: Only one auto column is allowed, and it must be designated as a primary key

I am facing an issue when running the following code in Laravel. I am trying to create a testimonial table using migration, but it seems like there is more than one primary key in the up() method. use Illuminate\Support\Facades\Schema; use ...

Enhance your Proguard and Gson skills by transforming variable names within an arraylist

During debugging, my code works perfectly fine. However, when I release my apk with Proguard 5, it obfuscates my variables. As a result, the string generated after "Jsonifying" is also obfuscated, causing issues with my PHP script. Here's an example ...

Empty Json Index

I have developed an Ionic application that communicates with my Laravel-based API by sending JSON data. Whenever a post request is made to the designated route, I invoke a method on my controller. This controller then takes the received data and stores i ...

Prevent Cross-Site Scripting attacks in Laravel by sanitizing user input, even when allowing HTML tags

What measures can be taken to protect against XSS attacks when a user is allowed to use HTML tags, such as in a textarea element? Avoiding the stripping or escaping of all tags complicates the situation and rules out the option of using {{ }}. It's a ...