public
Last active

darabase app example

  • Download Gist
gistfile1.pl
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
#!/usr/bin/env perl
 
use Mojolicious::Lite;
 
# connect to database
use DBI;
my $dbh = DBI->connect("dbi:SQLite:database.db","","") or die "Could not connect";
 
# shortcut for use in template
helper db => sub { $dbh };
 
# setup base route
any '/' => 'index';
 
my $insert;
while (1) {
# create insert statement
$insert = eval { $dbh->prepare('INSERT INTO people VALUES (?,?)') };
# break out of loop if statement prepared
last if $insert;
 
# if statement didn't prepare, assume its because the table doesn't exist
warn "Creating table 'people'\n";
$dbh->do('CREATE TABLE people (name varchar(255), age int);');
}
 
# setup route which receives data and returns to /
post '/insert' => sub {
my $self = shift;
my $name = $self->param('name');
my $age = $self->param('age');
$insert->execute($name, $age);
$self->redirect_to('/');
};
 
app->start;
 
__DATA__
 
@@ index.html.ep
% my $sth = db->prepare('SELECT * FROM people');
% $sth->execute;
 
<!DOCTYPE html>
<html>
<head><title>People</title></head>
<body>
<form action="<%=url_for('insert')->to_abs%>" method="post">
Name: <input type="text" name="name"> Age: <input type="text" name="age"> <input type="submit" value="Add">
</form>
<br>
Data: <br>
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
% while (my $row = $sth->fetchrow_arrayref) {
<tr>
% for my $text (@$row) {
<td><%= $text %></td>
% }
</tr>
% }
</table>
</body>
</html>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.