Jump to content

Problem assign $_POST value to variable


doubledee

Recommended Posts

If I had this

$_post['name'];

name would be considered the index of the post array. The index is whatever is inside of the bracket for post, get, request etc.

 

So what is wrong then?

 

My index is there...

 

<?php
// Initialize variables.
$attendeeName = $form_value = '';
$form_value = $_POST['form_value'];
echo '<br />CURRENT POST[form_value] = ' . $form_value;
echo '<br />CURRENT SESSION[form_value] = ' . $_SESSION['form_value'] . '<br />';

 

 

<!-- HTML PAYMENT FORM -->
<form id="payment" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

<!-- NEW -->
<label>SET NEW FORM VALUE:</label>
<input type="input" name="form_value" id="form_value"
			 value="<?php echo $_SESSION['form_value'];?>" />

 

 

 

Debbie

 

You aren't checking to see if $_POST['form_value'] exists before trying to access its value.

 

Conventional syntax:

if( isset($_POST['form_value']) ) {
     $form_value = $_POST['form_value'];
} else {
     $form_value = '';
}

 

Ternary syntax:

$form_value = isset($_POST['form_value']) ? $_POST['form_value'] : '';

You aren't checking to see if $_POST['form_value'] exists before trying to access its value.

 

Why do you have to do that?

 

In most languages, $form_value would just equal null if $_POST['form_value'] - or any variable - did not exist, right?!

 

 

Debbie

 

No, in most languages $_POST["form_value"] would be whatever the folks who designed the language felt like making it. It could be a pie if they so wanted it.

 

In PHP if you try to access an item in an array that does not exist then you get a warning.

Warnings are not, strictly speaking, errors.  A warning tells you that your code is designed wrong.  In this particular instance, PHP is letting you know that you're not checking to see if an array element exists before you try to use it.  $form_value will indeed be null, because you've accessed an array element that doesn't exist.  More correct code:

$form_value = null;
if ( isset( $_POST['form_value'] ) )
{
  $form_value = $_POST['form_value'];
}

//or more simply:
$form_value = isset( $_POST['form_value'] ) ? $_POST['form_value'] : null;

 

Also, this code is wrong:

$attendeeName = $form_value = '';

Don't chain assignments like that, it's ambiguous and wastes memory. edit: unless of course you're doing this specifically to empty both variables, then it's fine.  If you ever do something like $a = $b = "something"; that's a waste.

 

-Dan

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.