Created
October 19, 2012 03:28
-
-
Save jberger/3916068 to your computer and use it in GitHub Desktop.
darabase app example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment