Jump to content

Recommended Posts

Posted

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

Posted

Try using var_dump to print information about the variable, to see what might be wrong. For example:

 

var_dump($_POST['selection']);

 

That'll print out the type and structure of the variable, letting you see how you should access it.

  • 2 weeks later...
Posted

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

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.