Jump to content

PHP Forms - Creating a shop problem


danieldrave

Recommended Posts

Hi Guys,

 

I'm trying to code some PHP in which a user selects a product by selecting a checkbox and then when they click on 'Add To Basket' it takes them to a shopping basket displays what they selected.

 

Here's the code:

 

<div id="main">

<form action="basket.php" autocomplete="off" name="formSubmit" method="post">

<div id="table">

<?php

$conn = pg_connect("host=db.dcs.aber.ac.uk port=5432 dbname=teaching user=csguest pass

word=*****");

 

$res = pg_query ($conn, "select * from CSGames order by refnumber");

 

<!-- TABLE HEADERS OMITTED -->

 

 

while ($a = pg_fetch_array($res))

{

echo "<tr>\n";

echo "<td><input type='checkbox' name='selection[]' value='$refnumber' /></td>";

for ($j = 0; $j < pg_num_fields($res); $j++)

{

echo "<td>\n" . $a[$j] . "</td>\n";

}

echo "</tr>";

}

 

echo "</table>\n\n";

 

echo "<input type='submit' name='send' value='Add to Basket' />";

 

?>

 

And the code for the 'shopping basket' page:

<?php foreach($_POST['selection'] as $refnumber)

{

echo "Game:" .$refnumber. "<br />";

}

?>

 

At the moment this is the only output I get... - 'Game:' - nothing afterwards...

 

I believe the problem relates to how I'm referencing the variable 'refnumber' but I'm not sure how to resolve this.

 

Thanks for the help guys,

Dan

Link to comment
Share on other sites

  • 2 weeks later...

First: echo "<td><input type='checkbox' name='selection[]' value='$refnumber' /></td>";

 

name='selection[]'

 

that's not a valid name in html, you can try name='selection$i' while $i changes inside the while:

 

$i = 1;

while ($a = pg_fetch_array($res))
{
echo "<tr>\n";
echo "<td><input type='checkbox' name='selection$i' value='$refnumber' /></td>";
for ($j = 0; $j < pg_num_fields($res); $j++)
{
echo "<td>\n" . $a[$j] . "</td>\n";
}
echo "</tr>";
$i++;
}
echo "<input type='hidden' name='num' value='$i' />";

 

and then you can read the data like this:

 

<?
        $i = 1;
        while ($i <= $_POST['num'])
                 echo "$i: ".$_POST['selection$i']." \n";
?>

 

.. good luck

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • 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.