Page 1 of 1

foreach problem

Posted: Sun Jan 25, 2004 5:58 pm
by partiallynothing
The below code works w/o errors:

Code: Select all

<?php
foreach($_POST as $varname => $value) {
	$formVars['$varname'] = trim($value);
	}	
?>
but when I try to call a variable that should have been created with it, I get an error. So, for instance, when I echo $formVars['logon'], i get an Undefined Variable Error.

My index.php page is simple:

Code: Select all

<?php
<html>
<head>
<title>PartiallyNothing</title>
</head>
<body>
<form name="logon" method="post" action="inc/common/FormHandler.php?logon=true">
  <p>
    <input name="logon" type="text" id="logon">
  </p>
  <p>
    <input name="password" type="password" id="password">
  </p>
  <p>    <input name="submit" type="submit" id="submit" value="Submit">
      </p>
</form>
</body>
</html>
?>
My form handler page looks like this:

Code: Select all

<?php
if (isset($_GET['logon'])) {

	//start a session
	session_start();
	
	//create form array
	foreach ($_POST as $varname => $value) {
		$formVars['$varname'] = trim($value);
	}
	
	//check for empty fields	
	if (empty($formVars['logon']) || empty($formVars['password'])) {
		echo 'Error: No username or password specified.';
		die();
		}
	
	//check for incorrect characters
	if (!eregi("^[a-z'-}*$", $formVars['logon']) || !eregi("^[a-z'-}*$", $formVars['password'])) {
		echo 'Error: You username and password can only contain alphebetic characters or "-" or ";"';
		die();
		}
	
	//check for length
	if (strlen($formVars['logon']) > 50 || strlen($formVars['password']) > 50) {
		echo 'Error: You username and password cannot exceed 50 characters.';
		die();
		}
	
	//encrypt password
	$formVars['password'] = md5($formVars['password'], $formVars['logon']);
	
	//connect to database
	include('inc/common/db_connect.php');
	
	//query databse
	$query = "INSERT INTO users VALUES (NULL, {$formVars['logon']}, {$formVars['password']})";
	@ mysql_query($query) or die (mysql_error());
	}
	
elseif (isset($_GET['logoff'])) {
	
	echo 'exicute logoff script';
	}
	
elseif (isset($_GET['register'])) {

	echo 'exicute register script';
	}
	
elseif (isset($_GET['updateprofile'])) {

	echo 'exicute update profile script';
	}
?>
I get back my first error: No username or password specified, so I think it's not creating the formVars array.

Can anyone figure out why this does not work?!

Thanks a lot!

Posted: Sun Jan 25, 2004 6:00 pm
by markl999
$formVars['$varname'] = trim($value); <-- try removing the single quotes otherwise PHP will evaluate it as a literal '$varname'

Posted: Sun Jan 25, 2004 6:01 pm
by partiallynothing
that fixed it; thanks!