Page 1 of 2

help with passing variables

Posted: Wed Jun 02, 2004 10:55 pm
by C_Calav
Hi guys,

what i have here is a catalog of a list of planes. when the user clicks on the 'order' link i want the AircraftName, Stock and scale variables to be sent over to the next page for that plane.

i have searched and searched and i still cant figure my problem out. i did mange to get it passing when they were in a textbox but not how it is at the moment.

is passing them in the URL the best option?

thanx for your help will be eagerly waiting to see how it is done!

Code: Select all

<html>
<body>

<?php
 
    $db = mysql_pconnect('*****, '*****', '*****') or die ("Could not connect to database");

    if (!$db)
    &#123;
     echo 'Error: Could not connect to database.  Please try again later.';
     exit;
    &#125;

    mysql_select_db('models') or die ("Could not select database!"); 

    $query = "select * from planes where P_Cat = 'WWII Fighters'";

    $result = mysql_query($query) or die (mysql_error()."<br />Couldn't execute query: $query");

    $num_results = mysql_num_rows($result);
  
    for ($i=0; $i <$num_results; $i++)
    &#123;
     $row = mysql_fetch_array($result);
     
     $P_Stock = $row&#1111;'P_Stock'];
     $P_Name = $row&#1111;'P_Name'];
     $P_Cat = $row&#1111;'P_Cat'];
     $P_Scale = $row&#1111;'P_Scale'];
  
    echo" <table width='520' border='1'> ";
    echo"   <tr>  ";
    echo"        <td width='80' height='15'>Aircraft:</td> ";
    echo"        <td colspan='5' > $P_Name </font></td> ";
    echo"   </tr> ";
    echo"   <tr>  ";
    echo"        <td height='15'>Stock#:</td> ";
    echo"        <td colspan='5'> $P_Stock </font></td> ";
    echo"   </tr> ";
    echo"   <tr>  ";
    echo"        <td height='15'>Scale:</td> ";
    echo"        <td colspan='5'> $P_Scale </font></td> ";
    echo"   </tr> ";
    echo"   <tr>  ";
    echo"        <td height='15'></td> ";
    echo"        <td colspan='5'> <a href='order.php'> Order </a> </td> ";
    echo"  </tr> ";	 
    echo"  </table> ";

     &#125; 

?>


</body>
</html>

Posted: Wed Jun 02, 2004 11:07 pm
by kettle_drum
If you go to the next page by a text link, then passing them in the url is the easy way to do thing, but if you go there by clicking a form button, or what could be a form button, then post is probably the best way,

You just need to pass the data using either the url or a form, and then use the value by using $_GET['var_name'] or $_POST['var_name'] depending on how you passed the data.

You also dont need to keep calling echo each line, you can just leave it open like:

Code: Select all

echo "
   line here

                   one here
<table><tr><td></td></tr></table>
and here
";

Posted: Thu Jun 03, 2004 12:53 am
by scorphus
You can use POST or GET as kettle_drum said, here is a worth reading tutorial: Passing Variables through forms (POST) and URLS (GET).

If you wish to pass an entire array through form or URLS, [php_man]serialize[/php_man](), [php_man]unserialize[/php_man](), [php_man]base64_encode[/php_man]() and [php_man]base64_decode[/php_man]() may be of a bit help, please browse these posts:Also, take a look to this script:

Code: Select all

<pre><?php
// Simulate a row from DB:
$row = array('P_Stock' => 'Stock',
	'P_Name' => 'Name',
	'P_Cat' => 'Categ',
	'P_Scale' => 'Scale'
);
// Serialize it and encode:
$str = base64_encode(serialize($row));
echo '<a href="' . $_SERVER['PHP_SELF'] . '?data=' . $str . '">Order</a>' . "\n\n";

// Decode and unserialize the string, if it was passed:
if (isset($_GET['data']))
	print_r(unserialize(base64_decode($_GET['data'])));
?></pre>
which outputs the following (after clicking the 'Order' link):

Code: Select all

&lt;pre&gt;&lt;a href="/lab/serialize.php?data=YTo0OntzOjc6I...iJTY2FsZSI7fQ=="&gt;Order&lt;/a&gt;

Array
(
    &#1111;P_Stock] =&gt; Stock
    &#1111;P_Name] =&gt; Name
    &#1111;P_Cat] =&gt; Categ
    &#1111;P_Scale] =&gt; Scale
)
&lt;/pre&gt;
The href= attribute was truncated to fit in browser's window. Of course you don't need to pass the entire data/row, maybe just the ID or stock # to then query the database again in elapsing of the order process.

But, as it seems to be an e-commerce application, some security should play a role. Passing data by URL, even encoding it, may be a risk as it can be changed by some wicked user. So I suggest you to setup a session (Session Handling Functions). There is a tutorial on this matter: Sessions with a Minor in User Logins.

Good luck :), I hope it helps!
- Scorphus

Posted: Thu Jun 03, 2004 1:12 am
by C_Calav
thanx kettle_drum and scorphus going to get onto it now!

Posted: Thu Jun 03, 2004 4:19 am
by C_Calav
scorphus and kettle_drum, thanx for your replys but i have a few more questions for you or anyone else that could answer them.

now if i use POST in my above situation, would that post ALL the feilds?

i mean, what i want is a link or button (depends weather use get or post) and then once that is clicked it will pull the variables relavant to that button over to the next page. now from what im understanding only GET would be able to do that. is that correct?

with POST it seems the only way to post from the form is via text boxes.. but i dont have any. can i post from anything else? i mean my data are in table cells.

thanx!

Posted: Thu Jun 03, 2004 4:44 am
by choppsta
You "could" pass all the variables via POST using hidden form fields (<input type="hidden" name="" value="">).

But, as has been mentioned above, the problem is that it would be very easy for someone to change these values going to the next page.

The best way to do it would probably be to just pass the primary key of the row selected in a GET request.

E.g. a URL such as: order.php?id=xxx

On the next page you then just use this id to pull out the information from the database that you need.

Posted: Thu Jun 03, 2004 4:53 am
by C_Calav
thanx choppsta!

that sounds like a good idea. i do not know how to use GET though. could someone please give me some help.

<a href='order1.php??P_Stock=<?=P_Stock?>'> ??

and if so, how do i got about setting up the nest page?

any help would be great!

Code: Select all

<html> 
<body> 

<?php 

    $db = mysql_pconnect('*****', '*****', '*****') or die ("Could not connect to database"); 

    if (!$db) 
    { 
     echo 'Error: Could not connect to database.  Please try again later.'; 
     exit; 
    } 

    mysql_select_db('models') or die ("Could not select database!"); 

    $query = "select * from planes where P_Cat = 'WWII Fighters'"; 

    $result = mysql_query($query) or die (mysql_error()."<br />Couldn't execute query: $query"); 

    $num_results = mysql_num_rows($result); 
  
    for ($i=0; $i <$num_results; $i++) 
    { 
     $row = mysql_fetch_array($result); 
      
     $P_Stock = $row['P_Stock']; 
     $P_Name = $row['P_Name']; 
     $P_Cat = $row['P_Cat']; 
     $P_Scale = $row['P_Scale']; 
  
    echo" <table width='520' border='1'> 
               <tr>  
                    <td width='80' height='15'>Aircraft:</td> 
                    <td colspan='5' > $P_Name </font></td> 
               </tr> 
               <tr>  
                    <td height='15'>Stock#:</td> 
                    <td colspan='5'> $P_Stock </font></td> 
              </tr> 
              <tr>  
                   <td height='15'>Scale:</td> 
                   <td colspan='5'> $P_Scale </font></td> 
             </tr> 
             <tr>  
                  <td height='15'></td> 
                 <td colspan='5'> 
        <a href='order1.php?P_Stock=<?=P_Stock?>'> Order </a></td> 
            </tr>   
            </table> "; 

       } 

?> 


</body> 
</html> 

?>

Posted: Thu Jun 03, 2004 2:49 pm
by scorphus
C_Calav wrote:(..) <a href='order1.php??P_Stock=<?=P_Stock?>'> ?? (..)
Almost. It should be:

Code: Select all

<a href="order1.php?P_Stock=<?php echo $P_Stock;?>">Order</a>
and in order.php you use $_GET['P_Stock'].

Run this example and you'll understand:

Code: Select all

<a href="<?php echo $_SERVER['PHP_SELF'];?>">Test 0</a> passing nothing<br/>
<a href="<?php echo $_SERVER['PHP_SELF'];?>?stock=17">Test 1</a> passing stock<br/>
<a href="<?php echo $_SERVER['PHP_SELF'];?>?name=tucano">Test 2</a> passing name<br/>
<a href="<?php echo $_SERVER['PHP_SELF'];?>?categ=fighter">Test 3</a> passing category<br/>
<a href="<?php echo $_SERVER['PHP_SELF'];?>?scale=4">Test 4</a> passing scale<br/>
<a href="<?php echo $_SERVER['PHP_SELF'];?>?stock=17&name=tucano&categ=fighter&scale=4">Test 5</a> passing all<br/>

<pre><?php
echo '$_GET is ';
if (!empty($_GET)) 
	print_r($_GET);
else
	echo 'empty';
?></pre>
- Scorphus

Posted: Fri Jun 04, 2004 3:24 am
by C_Calav
thank you very much scorphus!!

im on holiday at the mo untill monday (new zealand public holiday) but will try when get home!

Posted: Fri Jun 04, 2004 4:25 am
by dave420
Passing variables by POST is better than by GET, as it is harder to manipulate them. It's also trivial to provide a check that the values haven't been tampered with (pass two variables, the first is the actual value, and the second is a hash of that value with a secret string. To check the validitiy of a variable, check the hash with a new calculated hash, and see if they match).

Also, passing strings like that around with GETs looks pretty messy :-P

Posted: Wed Jun 09, 2004 8:09 pm
by C_Calav
thanx for that dave420, BUT how can i do what i wanna do with POST? can you give me an example like scorphus did but with POST instead of GET?

Thnx

Posted: Wed Jun 09, 2004 8:13 pm
by tim
the only difference

generally n genericly speaking, GET is to 'get' var values from the urls, POST is to get var values from forms n such.

no magic in either of them.

Posted: Wed Jun 09, 2004 10:43 pm
by C_Calav
thanx tim, but what if i want 'specific' vars to be passed to the next page, i cant use POST can i? i mean, for example,

Form
P_Stock (1)
P_Stock (2)
P_Stock (3) <-----
P_Stock (4)
P_Stock (5)
P_Stock (6)

now if i want to get P_Stock (3) to the order page and populate some feilds i can only get that there by GET or am i wrong? becoz if i use POST how do i specifally get just that one over ... any examples would be great! thats what started this post! sorry if im confusing anybody

Posted: Thu Jun 10, 2004 3:51 am
by dave420
You can use post. I use it commonly, when I want to send data back to a script in a tidy way (query strings, to me at least, are horribly ugly). You can use a form and a small bit of cross-platform javascript to populate it from an HREF or any javascript event.

Posted: Thu Jun 10, 2004 4:53 pm
by scorphus
C_CalavTake this example and see how it is simple:

Code: Select all

<html>

<head>
	<title>Post example</title>
</head>

<body>

<strong>Post example</strong>

<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>" method="post">
	<input type="hidden" name="hiddenField" value="This one is not show">
	<p>Text field: <input type="text" name="textField" value="This is a text field"></p>
	<!-- Note the [] in name attributes of the radio and checkbox fields. Also note the
	use of <label> tags in the radio and checkbox esamples below, you can note the effect
	only in Mozilla (http://www.mozilla.org), dumb IE does not work as expected -->
	<p>Radio group:<br />
	<label><input type="radio" name="radioFields[]" value="This is the radio field 1"> Radio 1</label><br />
	<label><input type="radio" name="radioFields[]" value="This is the radio field 2"> Radio 2</label><br />
	<label><input type="radio" name="radioFields[]" value="This is the radio field 3"> Radio 3</label><br />
	<label><input type="radio" name="radioFields[]" value="This is the radio field 4"> Radio 4</label></p>
	<p>Checkbox group:<br />
	<label><input type="checkbox" name="checkboxes[]" value="This is the checkbox field 1"> Checkbox 1</label><br />
	<label><input type="checkbox" name="checkboxes[]" value="This is the checkbox field 2"> Checkbox 2</label><br />
	<label><input type="checkbox" name="checkboxes[]" value="This is the checkbox field 3"> Checkbox 3</label><br />
	<label><input type="checkbox" name="checkboxes[]" value="This is the checkbox field 4"> Checkbox 4</label></p>
	<p>Select field: <select name="selectField">
		<option value="option 1">option 1</option>
		<option value="option 2">option 2</option>
		<option value="option 3">option 3</option>
		<option value="option 4">option 4</option>
	</select></p>
	<p>Text area:<br />
	<textarea rows="5" cols="50" name="textArea">Text area</textarea></p>
	<!-- Use to name the submit filed of your form something that is not 'submit'
	this way you can call the form's submit() function in JavaScript -->
	<input type="submit" name="btnsubmit">
	<input type="reset" name="btnreset">
</form>

<pre>
$_POST: <?php
if (empty($_POST))
	echo 'empty';
else
	print_r($_POST);
?>
</pre>

</body>
</html>
Scorphus.