#!/usr/bin/php-cgi -dcgi.force_redirect=0
<?php
# encoding: utf-8
# api: cgi
# type: store
# category: database
# title: Survey submit
# description: Store simple POST form data into database survey_* table
# version: 0.1
# state: alpha
# config: -
#
# Requires a form like:
#
# <action target="/extroot/survey/SAMPLE" method=POST>
# <input type=checkbox name=q1>
# <input type=radio name=q2>
# <input type=text name=q3>
#
# And will then populate a `survey_SAMPLE` table with JSON entries (no
# field expansion or anything).
#
#-- database (== fossil repo)
function db($sql="", $params=[]) {
static $db;
if (empty($db)) {
$db = new PDO("sqlite:$_SERVER[FOSSIL_REPOSITORY]");
}
if ($params) {
$stmt = $db->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
else {
return $db->query($sql)->fetchAll();
}
}
#-- insert
function store() {
$tbl = preg_replace("/\W+/", "", basename($_SERVER["PATH_INFO"]));
if (!$tbl) {
die("No table name given /survey/NAME");
}
else {
$json = json_encode($_POST);
db("CREATE TABLE IF NOT EXISTS `survey_$tbl` (submitted DATETIME, remote_addr, fields TEXT)");
db("INSERT INTO `survey_$tbl` (submitted, remote_addr, fields) VALUES (NOW(), ?, ?)", [$_SERVER["REMOTE_ADDR"], $json]);
}
}
#-- run
if (count($_POST)) {
store();
}
else {
die("Empty form");
}