Jump to content

PHP Forms - Creating a shop problem

Featured Replies

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

  • 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

Archived

This topic is now archived and is closed to further replies.

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.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.