TripletaiL Japanese Web Application Framework

MySQLの利用(2) - チュートリアル

DBに接続し、SELECT文を発行し、情報を取得してみましょう。

以下を前提条件とします。

main.cgi

#!/usr/local/bin/perl

use strict;
use warnings;
use Tripletail qw(tl.ini);

$TL->startCgi(
    -DB => 'DB',
    -main => \&main,
);

sub main
{
    $TL->dispatch($CGI->get('Command'), default => 'Top');
}

sub DoTop
{
    &DispTop;
}

sub DoWriteAfter
{
    &DispWriteAfter;
}

sub DoWrite
{
    &WriteDB;
    $TL->location($TL->newForm->set(Command => 'WriteAfter')->toLink);
}

sub WriteDB
{
    my $DB = $TL->getDB('DB');
    my $sth = $DB->execute(q{
        INSERT INTO
            TripletaiL_DB_Test (val1, val2)
        VALUES
            (?, ?)
    }, $CGI->getSliceValues(qw(word radio)));
}

sub DispWriteAfter
{
    my $t = $TL->newTemplate('write_after.html', 'utf8');
    my $DB = $TL->getDB('DB');

    my $hash = $DB->selectAllHash(q{
        SELECT
            val1,
            val2
        FROM
            TripletaiL_DB_Test
    });

    foreach my $key (@$hash) {
        $t->node('list')->node('val1')->add(
            VAL => $key->{val1},
        );
        $t->node('list')->node('val2')->add(
            VAL => $key->{val2},
        );
        $t->node('list')->add;
    }
    $t->flush;
}

sub DispTop
{
    my $t = $TL->newTemplate('write.html', 'utf8');
    $t->addHiddenForm($TL->newForm->set(Command => 'Write'));
    $t->flush;
}

tl.ini

[TL]

[DB]
type = mysql
defaultset = SET_Default
SET_Default = CON_DBRW

[CON_DBRW]
host = localhost
user = user
dbname = test
password = pass

write.html

<!DOCTYPE html>
<HTML>
  <BODY>
    <form method="post">
      <input type="text" name="word">
      <br>
      <input type="radio" name="radio" value="1">
      <input type="radio" name="radio" value="2">
      <br>
      <input type="submit" name="submit" value="送信">
    </form>
  </BODY>
</HTML>

write_after.html

<!DOCTYPE html>
<HTML>
  <BODY>
    <!begin:list>
      <!begin:val1>
        テキストエリア : <&VAL>,
      <!end:val1>
      <!begin:val2>
        ラジオボタン : <&VAL>,
      <!end:val2>
      <BR>
    <!end:list>
  </BODY>
</HTML>

一覧へ戻る 次のチュートリアルへ