Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
darabase app example
#!/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);
@@ index.html.ep
% my $sth = db->prepare('SELECT * FROM people');
% $sth->execute;
<!DOCTYPE html>
<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">
Data: <br>
<table border="1">
% while (my $row = $sth->fetchrow_arrayref) {
% for my $text (@$row) {
<td><%= $text %></td>
% }
% }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment