Page 1 of 2

Need help in passing data from a form

Posted: Mon Mar 19, 2007 3:47 pm
by pendragon
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I am new to PHP and am having trouble getting data from the form to my second page.

None of these seem to work:

 $course = $_REQUEST['course$i']
 $course = $_REQUEST['course']
 $course = $_REQUEST["course$i"]
 $course = $_REQUEST["course"]

What am I doing wrong?

Code: Select all

<html>
  <head>
    <title>Semester GPA Calculator</title>
    <style type='text/css'>
      th {text-align: left;}
    </style>
  </head>
  <body>
  <h2>Semester GPA Calculator</h2>
  <p>Please enter your course information:</p>
  <form action='script_semesterGPAT.php' method='post'>
  <table width='50%'>
  <tr><th>Course</th><th>Units</th><th>Letter Grade</th></tr>
  <?php
  for ($i=0; $i<5; $i+=1) {
    print "<tr>\n";
    print "\t<td><input type='text' name='course$i'></td>\n";
    print "\t<td><input type='text' name='units$i' size=5></td>\n";
    print "\t<td><input type='text' name='letterGrade$i' size=5></td>\n";
    print "</tr>\n";
  }
  ?>
  </table>
  <input type='submit' value='Calculate GPA'>
  </form>
  </body>
</html>

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Mon Mar 19, 2007 4:10 pm
by feyd
The double quote version with $i, provided $i is defined, should work.

Posted: Mon Mar 19, 2007 4:18 pm
by RobertGonzalez
The same logic used to display the form fields should work to process the post vars (use $_POST, not $_REQUEST) in conjunction with the $i var.

Still not working

Posted: Mon Mar 19, 2007 4:54 pm
by pendragon
Here's a sample second page I used to test for retrieval of the variables.

All that get's printed out is the table header. No data gets displayed.

Code: Select all

<?php	

 // Retrieving the Form Variables 
	   $courses = $_POST["course$i"];
	   $units = $_POST["units$i"];
	   $grades = $_POST["letterGrade$i"];
?>


<html>
<head>
<title>Test to get variables from form</title>
</head>
<body>	
  
<?php	
    print "<table width = 90% border = '1' cellspacing = '5' cellpadding = '0'>";
	//     Create horizontal header for Table
	   print "<tr><th>Course</th><th>Units</th><th>Letter Grade</th></tr>";	   
	   // loop to create rows 
	      // get number of user entered courses
		      $num_rows = count($courses);
			  for ($i= 0; $i < $num_rows; $i++)
                                                 {
			     //  Prints Row Info 
			         print("<tr><td>$courses[$i]</td></tr>");
			  }	
   print "</table>\n";                                                                 
?>
</body>
</html>

Posted: Mon Mar 19, 2007 5:11 pm
by RobertGonzalez

Code: Select all

<?php   
echo '<table width="90%" border="1" cellspacing="5" cellpadding="0">';
//     Create horizontal header for Table
echo '<tr><th>Course</th><th>Units</th><th>Letter Grade</th></tr>';
// loop to create rows
// get number of user entered courses
/**
 * THIS WILL NOT WORK OUT THE WAY YOU EXPECT AS COURSES WAS 
 * DEFINED AS $_POST["courses$i"]. $i HAD NOT BEEN SET YET SO THAT 
 * VALUE WILL LIKEWISE NOT BE SET TO ANYTHING USEABLE
 */
$num_rows = count($courses);

/**
 * TO MAKE THIS WORK YOU NEED TO USE THE SAME LOGIC AS WHAT 
 * WAS USED TO DISPLAY THE FORM ELEMENTS
 */
//for ($i= 0; $i < $num_rows; $i++)
for ($i= 0; $i < 5; $i++)
{
    //  Prints Row Info
    echo '<tr><td>' . $_POST['courses' . $i] . '</td></tr>';
}     
echo "</table>\n";                                                                 
?>

Posted: Mon Mar 19, 2007 5:22 pm
by pendragon
Thanks Everah for the reply.

However, when I tried your solution using the original form and posting entered info to your secondary page, I still only
get a table header printed out with no data or values.

I must be tired because I usually don't get hung up on the details - can't get past this one today.

Posted: Mon Mar 19, 2007 5:29 pm
by RobertGonzalez
Have a look see at what is coming out of the form. Do this:

Code: Select all

<?php
var_dump($_POST);
?>
<html>
<head>
<title>Test to get variables from form</title>
</head>
<body> 
Testing something out real quick...
</body>
</html>
Make this a new result page, change your form action to this new page, then process the form. Lets see what is coming out of it.

Heres the results of the dump

Posted: Mon Mar 19, 2007 5:35 pm
by pendragon

Code: Select all

array(15) { ["course0"]=> string(8) "Course 1" ["units0"]=> string(1) "3" ["letterGrade0"]=> string(1) "A" ["course1"]=> string(8) "Course 2" ["units1"]=> string(1) "3" ["letterGrade1"]=> string(1) "A" ["course2"]=> string(9) "Course 3 " ["units2"]=> string(1) "2" ["letterGrade2"]=> string(1) "A" ["course3"]=> string(8) "Course 4" ["units3"]=> string(1) "2" ["letterGrade3"]=> string(1) "A" ["course4"]=> string(8) "Course 5" ["units4"]=> string(1) "1" ["letterGrade4"]=> string(1) "A" } Testing something out real quick...

Posted: Mon Mar 19, 2007 6:10 pm
by RobertGonzalez
So then, you have an array being passed that looks like this...

Code: Select all

<?php
$_POST = array( 
	["course0"]=> "Course 1",
	["units0"]=> "3", 
	["letterGrade0"]=> "A", 
	["course1"]=> "Course 2", 
	["units1"]=> "3", 
	["letterGrade1"]=> "A", 
	["course2"]=> "Course 3 ", 
	["units2"]=> "2", 
	["letterGrade2"]=> "A", 
	["course3"]=> "Course 4", 
	["units3"]=> "2", 
	["letterGrade3"]=> "A", 
	["course4"]=> "Course 5", 
	["units4"]=> "1", 
	["letterGrade4"]=> "A" 
);
?>
That means that you can rifle through that array var doing something like this...

Code: Select all

<?php
// Set up array holder 
$form_info = array();

// Set default count for the data
$count = 0;

// This is an index for our arrays, so they correlate...
$c = 0;
if (!empty($_POST))
{
    foreach ($_POST as $k => $v)
    {
        if (stristr('course', $k))
        {
            $form_info[$c]['course'] = trim($v);
        }
        elseif (stristr('units', $k))
        {
            $form_info[$c]['units'] = trim($v);
        }
        else
        {
            $form_info[$c]['grade'] = trim($v);
        }
        
        $c++;
    }
    
    $count = count($form_info);
}    
?>
<html>
<head>
<title>Test to get variables from form</title>
</head>
<body> 
<table width="90%" border="1" cellspacing="5" cellpadding="0"> 
<tr><th>Course</th><th>Units</th><th>Letter Grade</th></tr>
<?php
if ($count > 0)
{
    for ($i = 0; $i < $count; $i++)
    {
        echo '<tr>';
        echo '<td>' . $form_info[$i]['course'] . '</td>';
        echo '<td>' . $form_info[$i]['units'] . '</td>';
        echo '<td>' . $form_info[$i]['grade'] . '</td>';
        echo '</tr>';
    }
}
else
{
    echo '<tr><td colspan="3">There is nothing to display</td></tr>';
}
?>
</table>
</body>
</html>
EDIT | I made my opriginal code a little cleaner.

PS You could even refer to each POST array member by its key to get its value...

Code: Select all

<?php
echo $_POST['course0'];
?>

Posted: Mon Mar 19, 2007 6:15 pm
by RobertGonzalez
I have a problem in my foreach. Hang on a second before using this.

EDIT | Man, was I stupid or what?!?! :?

Try this one:

Code: Select all

<?php
// Set up array holder
$form_info = array();

// Set default count for the data
$count = 0;

if (!empty($_POST))
{
    for ($c = 0; $c < 5; $c++)
    {
        $form_info[$c]['course'] = isset($_POST['course' . $c]) ? ($_POST['course' . $c] : '';
        $form_info[$c]['units'] = isset($_POST['units' . $c]) ? $_POST['units' . $c] : '';
        $form_info[$c]['grade'] = isset($_POST['letterGrade' . $c]) ? $_POST['letterGrade' . $c] : '';;
    }
   
    $count = count($form_info);
}   
?>
<html>
<head>
<title>Test to get variables from form</title>
</head>
<body>
<table width="90%" border="1" cellspacing="5" cellpadding="0">
<tr><th>Course</th><th>Units</th><th>Letter Grade</th></tr>
<?php
if ($count > 0)
{
    for ($i = 0; $i < $count; $i++)
    {
        echo '<tr>';
        echo '<td>' . $form_info[$i]['course'] . '</td>';
        echo '<td>' . $form_info[$i]['units'] . '</td>';
        echo '<td>' . $form_info[$i]['grade'] . '</td>';
        echo '</tr>';
    }
}
else
{
    echo '<tr><td colspan="3">There is nothing to display</td></tr>';
}
?>
</table>
</body>
</html>

Getting there but not yet

Posted: Mon Mar 19, 2007 6:37 pm
by pendragon
Thanks for the help. Since I'm fairly new to PHP, I'll have to chew on the response a bit.
If I can capture the form values on a second page, then I can take it from there.

Your last entry , when used as the secondary page, throws an error:


It gives: Parse error: parse error, unexpected ':' in C:\wamp\www\CS130A-S07\test2.php on line 12


That would be the following line:


$form_info[$c]['course'] = isset($_POST['course' . $c]) ? ($_POST['course' . $c] : '';

Posted: Mon Mar 19, 2007 7:01 pm
by RobertGonzalez
Sorry, For some reason I decided to add a opening paren for no reason. Let me fix that...

Code: Select all

<?php
// Set up array holder
$form_info = array();

// Set default count for the data
$count = 0;

if (!empty($_POST))
{
    for ($c = 0; $c < 5; $c++)
    {
        $form_info[$c]['course'] = isset($_POST['course' . $c]) ? $_POST['course' . $c] : '';
        $form_info[$c]['units'] = isset($_POST['units' . $c]) ? $_POST['units' . $c] : '';
        $form_info[$c]['grade'] = isset($_POST['letterGrade' . $c]) ? $_POST['letterGrade' . $c] : '';
    }
   
    $count = count($form_info);
}   
?>
<html>
<head>
<title>Test to get variables from form</title>
</head>
<body>
<table width="90%" border="1" cellspacing="5" cellpadding="0">
<tr><th>Course</th><th>Units</th><th>Letter Grade</th></tr>
<?php
if ($count > 0)
{
    for ($i = 0; $i < $count; $i++)
    {
        echo '<tr>';
        echo '<td>' . $form_info[$i]['course'] . '</td>';
        echo '<td>' . $form_info[$i]['units'] . '</td>';
        echo '<td>' . $form_info[$i]['grade'] . '</td>';
        echo '</tr>';
    }
}
else
{
    echo '<tr><td colspan="3">There is nothing to display</td></tr>';
}
?>
</table>
</body>
</html>

That Worked!

Posted: Mon Mar 19, 2007 7:22 pm
by pendragon
Thanks Everah!

That Worked! A thousand blessings on your head. I need a bit of time tonight to digest your code.

If I have any additional questions, I'll post them later on tonight or early tomorrow and hopefully you can check in to see if
I'm going in the right direction.

Thanks for the PHP lesson. I especially appreciated the bit of code for checking values coming out of a form. I'll keep that handy for future use.

Your effort was tremendous!

Best Regards!

Before I retreat to digest

Posted: Mon Mar 19, 2007 8:14 pm
by pendragon
One last question before I head to my corner...

Code: Select all

$form_info[$c]['course'] = isset($_POST['course' . $c]) ? $_POST['course' . $c] : '';

This piece of code is a bit more sophisticated than my beginner books cover.

Could you explain it a bit? Is it a conditional statement? Is there a simpler way to write it?

Re: Before I retreat to digest

Posted: Tue Mar 20, 2007 11:15 am
by RobertGonzalez
pendragon wrote:One last question before I head to my corner...

Code: Select all

$form_info[$c]['course'] = isset($_POST['course' . $c]) ? $_POST['course' . $c] : '';
This piece of code is a bit more sophisticated than my beginner books cover.

Could you explain it a bit? Is it a conditional statement? Is there a simpler way to write it?
Yes, it is a conditional statement called a ternary. It can also be written like this:

Code: Select all

<?php
if (isset($_POST['course' . $c]))
{
    $form_info[$c]['course'] = $_POST['course' . $c];
}
else
{
    $form_info[$c]['course'] = '';
}
?>
It isn't something that I use unless it in plainly clear what the intent of the conditional is. There are quite a few things happening in your code that you should note make your code less than secure. But for testing, what you have is adequate. But I would really add some validation to your variables being passed before echoing anything to the screen.