1 #!/usr/bin/perl 2 3 use DBI; 4 require 'jcode.pl'; 5 6 $user = 'test'; 7 $passwd = 'test2001'; 8 $db = DBI->connect('DBI:mysql:ATMARKIT:localhost', $user, $passwd); 9 10 # FORMからデータを読み込む 11 $len = $ENV{'CONTENT_LENGTH'}; 12 read(STDIN, $std, $len); 13 @args = split(/&/, $std); 14 foreach $arg ( @args ){ 15 ($name, $val ) = split(/=/, $arg); 16 $val =~ s/\+/ /g; 17 $val =~ s/%([0-9a-f][0-9a-f])/pack('C', hex($1))/egi; 18 &jcode'convert(*val, 'euc'); 19 $form{$name} = $val; 20 } 21 22 print <<HEADER; 23 Content-type: text/html 24 25 26 <html> 27 <head> 28 <META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=x-euc-jp"> 29 <title>Sample MySQL+Perl</title> 30 </head> 31 <body> 32 HEADER 33 34 if($form{command} eq 'select' || $form{command} eq 'delete'){ 35 if($form{name} ne '' ){ 36 $where .= "name like '\%$form{name}\%'"; 37 } 38 if($form{name} ne '' && $form{memo} ne ''){ 39 $where .= " and " 40 } 41 if($form{memo} ne '' ){ 42 $where .= "memo like '\%$form{memo}\%'"; 43 } 44 45 if($where ne ''){ 46 $where = "WHERE " . $where; 47 } 48 49 if($form{command} eq 'select'){ 50 $sth = $db->prepare("SELECT name, memo FROM list $where"); 51 $sth->execute; 52 $num_rows = $sth->rows; 53 print "<h1>該当 $num_rows 件</h1>"; 54 for ($i=0; $i<$num_rows; $i++) { 55 @a = $sth->fetchrow_array; 56 print "<h2>name=$a[0] memo=$a[1]</h2>"; 57 } 58 $sth->finish; 59 } 60 if($form{command} eq 'delete'){ 61 $sth = $db->prepare("delete FROM list $where"); 62 $sth->execute; 63 print "<h1>削除完了</h1>"; 64 $sth->finish; 65 } 66 67 }elsif($form{command} eq 'insert'){ 68 if($form{name} eq '' ){ 69 print "<h1>nameが空白では登録できません</h1>"; 70 }else{ 71 $sth = $db->prepare("insert into list (name,memo) values ('$form{name}','$form{memo}')"); 72 $sth->execute; 73 print "<h1>登録完了</h1>"; 74 $sth->finish; 75 } 76 } 77 78 $db->disconnect; 79 80 print <<FOOTER; 81 </body> 82 </html> 83 FOOTER
Copyright © ITmedia, Inc. All Rights Reserved.