thebarless thebarless - 9 months ago 41
PHP Question

Can't set variable from $_POST

I can't set a variable from a post array.

I have a simple form with a hidden field in it:

<input name="sid" type="hidden" id="sid" value="<?=$sid?>">

This hidden field gets sent off to a second file (exec.php) where I have the following code:

$sid = $_POST['sid'];

For some reason, when trying to set $sid, it gets a NULL value. For haha's, I ran the following:

foreach($_POST as $var => $value)
echo $var . ' : ' . $value . "<br>";

This provided a correct value of 1938 for sid. I've looked at this for 3 hours and can't find what is happening. I expect something extremely stupid...any thoughts?

Here is the form on enter.php

<form name="form1" method="post" action="exec.php">
<input name="sid" type="hidden" id="sid" value="<? echo($sid); ?>">
<input name="ticket_totals" type="hidden" id="ticket_totals" value="<?=$ticket_totals?>">
<input name="emp" type="hidden" id="emp" value="<?=$emp?>">
<input name="submit" type="submit" id="submit" value="Submit">
<input type="submit" name="submit" id="submit" value="Close">

Here is the POST output on exec.php:
type : Other
ticket_totals : 0
emp : 105
sid : 1939
submit : Submit

Okay - this was poor syntax on my part but now I'm curious as to why.

I left out quotation marks - the solution is as simple as this:
$sid = $_POST["sid"]

Now it works like a champ.

Any takers on why? I'd guess there is a setting in the php.ini that requires the quotes. Strangely enough, I have other variables called from the POST array that i'm not using quotes for and they're working fine...

Answer Source

Use Console in FireBug to inspect the POST request to see what is the sid value that is being sent.

If the sid value in request is ok, use var_dump($_POST["sid"]); to see the results on the server.

EDIT: it's considered good PHP style to use the quotes when accessing the associative array because quote-less keys are indistinguishable from constants:

echo $array[myVar]; // retrieves $array[3], not $array['myVar'];