CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Advanced:
Insert into table when user clicks one of many submit buttons

 



jwalker
Novice

Nov 27, 2011, 2:29 PM

Post #1 of 2 (3455 views)
Insert into table when user clicks one of many submit buttons Can't Post

Hi,I am trying to create a site that sells music. I have page with a list of tracks, each with a submit button to buy the track. When a user clicks on one of the submit buttons, the catalog number gets inserted into a table called cart. The problem is that whichever submit button is pressed, only the first row is inserted.
Each line of the form has a hidden field with a value of the row from the tracks table in the database. Here is the code I have so far:
foreach ($cgi_object->param())
{
$form{$_} = $cgi_object->param($_);
$catnum = $form{cat_num};
$row = $form{id};
}
my $insert=qq~ insert into cart (id,cat_num) select id,catalog_num from tracks where id ='$row'~;
my $dbh=DBI->connect($connectionInfo,$user,$passwd);
my $sth=$dbh->prepare($insert);
$sth->execute();
When I execute the mysql statement in the database and replace $id with a row number I get the desired result. I'm guessing the problem has something to do with putting the insert into a loop? Not sure quite how to do this. Any help would be much appreciated. Thanks.


budman
User

Feb 12, 2012, 1:41 PM

Post #2 of 2 (2926 views)
Re: [jwalker] Insert into table when user clicks one of many submit buttons [In reply to] Can't Post

You may want to familiarize yourself with some online shopping cart docs.
Especially how to sanitize the data between the web and your internal system.

I am assuming you have a form setup, with multiple checkboxes one for each track. The checkboxes should all use the same group name (ie. 'id'). When you click submit, store the param 'id' into an array.

(not tested)


Code
  
use HTML::Entities ();
use CGI qw/:standard/;

# get form data
# sanitize params to avoid arbitrary code

my $ok_chars = '0-9'; # limit param values to digits
my @items = $cgi_object->param('id');
foreach my $i ( 0 .. $#items ) {
my $id = HTML::Entities::decode( $items[$i] );
$id =~ s/[^$ok_chars]//go;
$items[$i] = $id;
}

# update database

my $dbh = DBI->connect($connectionInfo,$user,$passwd);
my $list = join("','", @items);
my $sql = "insert into cart (id,cat_num)
select id,catalog_num
from tracks where id in ('$list')";
my $sth=$dbh->prepare($sql);
$sth->execute();


http://advosys.ca/papers/web/61-web-security.html
http://www.cgi101.com/book/ch5/text.html


(This post was edited by budman on Feb 12, 2012, 3:10 PM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives