Jump to content

Recommended Posts

Hello, my global variable is getting whacked (defined null or being undefined) after a function call.  I'm not sure if it's happening when leaving the function that assigns it or when the form is "posted", or something else.

 

<?
//global variables
$globalVarString = "";

//function definitions
function displayResults()
{
   global $globalVarString;

   if ($globalVarString == "") {displayForm("please enter your search string again");}
   else {displayForm("you typed: $globalVarString");}
}

function getResults($searchInput)
{
   global $globalVarString;
   $globalVarString = $searchInput;

   //give status
   ?>
     <html><head><title>Search</title></head><body>
     <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
     Thanks for entering your data (<? echo "$globalVarString" ?>).<br><br>Please press the submit button to process your data &nbsp&nbsp
     <input type="Submit" value="Submit" name="processQuery">
     </form></body></html>
   <?
   }

function displayForm($message)
{
   //prompt for input
   ?>
     <html><head><title>Search</title></head><body>
     <form action=" <? $_SERVER['PHP_SELF'] ?>" method="post">
     <h3>Please enter your search <input type="text" name="searchString"> &nbsp&nbsp
     <script type="text/javascript">document.forms[0].searchString.focus();</script>
     <input type="Submit" value="Submit Query" name="searchQuery"></h3>
     </form>
     <? if (!$message == ""){echo "<br> &nbsp&nbsp <h4>" . $message . "</h4><br>";} ?>
     </body></html>
   <?
}

//main()
if(array_key_exists('searchQuery', $_POST)) {getResults($_POST['searchString']);}
elseif (array_key_exists('processQuery', $_POST)) {displayResults();}
else {displayForm("");}
?>

1. The proper tags for PHP are <?php ?>.  You're not guaranteed that the shorthand tags will work, so never use them.

 

2. Never use the 'global' keyword.  Functions have an argument list for a reason.  Pass all parameters necessary for a function to work through the argument list.

 

3. Your global is superfluous.  You don't need it in your case at all.  Simply use $searchInput.

 

4. Try basic debugging techniques.  Write echo statements to track your variable through the form submission process.

Nightslyr:  I  changed the tags, thanks.  I have used echo statements to track the global variable, still  no luck.  Regarding your points 2 and 3:  If I can't use global variables between functions then why is the (global) language construct there?

 

my posted code is just an example, the real code is 761 lines long so I didn't post it but it's basically doing the same thing:

1)  display a form to accept user input

2)  searching a database for all fields "like" the search input

      a)  if results are found assign them to a global variable named after the field.

3)  The form is displayed again, this time with links, as submit buttons, from database query in step 2a.

4)  When the user clicks on a link the results are displayed (from the global variable) to either a web page or exported to excel.

5)  The code is failing on step 4 because the global variable is null, so what I'm having to do is requery the db, based on the  link name the user clicked to display the results.  This is unsatisfactory, thought there might be a solution so I checked here.

 

The db query data could be thousands of entries long so I decided to assign them to global variables instead of passing them as function arguments, to avoid any function paramater character limits.  But, if I can't use global variables then I guess I'll have to rethink my algorithm.

Regarding 'global', just because you can do something doesn't mean you should.  'Global' is frowned upon for the very reasons you're experiencing - it makes things incredibly difficult to debug because the value can be changed at any time.  It also ties the proper execution of a function to the context in which it was invoked.  Functions are supposed to be general purpose, where they take certain values from the outside, process them in a certain way, and return a result.  'Global' adds an extra, and hidden to the outside/main script, constraint. 

 

Good code adheres to explicit lines of communication.  With functions, that means using their argument lists as intended and not adding extra, hidden caveats via 'global.'

 

And, if you need to pass an unknown number of arguments into a function, use an array.

 

Your algorithm is flawed because you're not taking into account HTTP's stateless nature.  Values are not retained between page refreshes.  Rather than stuffing results in a generic global variable, put them in sessions (also an array) to keep them between page refreshes.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.