Skip to content
Snippets Groups Projects
Commit d5bc58c3 authored by Sergey Lyubka's avatar Sergey Lyubka
Browse files

Using sqlite as an example

parent 51a80e48
No related branches found
No related tags found
No related merge requests found
<html> <?
<p>Prime numbers from 0 to 100, calculated by Lua:</p> -- Lua server pages have full control over the output, including HTTP
<? -- headers they send to the client. Send HTTP headers:
print('HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n')
?><html><body>
function is_prime(n) <p>This is an example Lua server page served by
if n <= 0 then return false end <a href="http://code.google.com/p/mongoose">Mongoose web server</a>.
if n <= 2 then return true end Mongoose has Lua, Sqlite, and other functionality built in the binary.
if (n % 2 == 0) then return false end This example page stores the request in the Sqlite database, and shows
for i = 3, n / 2, 2 do all requests done previously.</p>
if (n % i == 0) then return false end
end
return true
end
for i = 1, 100 do <pre>
if is_prime(i) then print('<span>' .. i .. '</span>&nbsp;') end <?
end -- Open database
local db = sqlite3.open('requests.db')
?> -- Setup a trace callback, to show SQL statements we'll be executing.
-- db:trace(function(data, sql) print('Executing: ' .. sql .. '\n') end, nil)
<p>Reading POST data from Lua (click submit):</p> -- Create a table if it is not created already
<form method="POST"><input type="text" name="t1"/><input type="submit"></form> db:exec([[
CREATE TABLE IF NOT EXISTS requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp NOT NULL,
method NOT NULL,
uri NOT NULL,
user_agent
);
]])
<pre> -- Add entry about this request
POST data: [<? post_data = read() print(post_data) ?>] local stmt = db:prepare(
request method: [<? print(request_info.request_method) ?>] 'INSERT INTO requests VALUES(NULL, datetime("now"), ?, ?, ?);');
IP/port: [<? print(request_info.remote_ip, ':', request_info.remote_port) ?>] stmt:bind_values(request_info.request_method, request_info.uri,
URI: [<? print(request_info.uri) ?>] request_info.http_headers['User-Agent'])
HTTP version [<? print(request_info.http_version) ?>] stmt:step()
HEADERS: stmt:finalize()
<?
for name, value in pairs(request_info.http_headers) do
print(name, ':', value, '\n')
end
?>
</pre>
-- Show all previous records
print('Previous requests:\n')
stmt = db:prepare('SELECT * FROM requests ORDER BY id DESC;')
while stmt:step() == sqlite3.ROW do
local v = stmt:get_values()
print(v[1] .. ' ' .. v[2] .. ' ' .. v[3] .. ' '
.. v[4] .. ' ' .. v[5] .. '\n')
end
</html> -- Close database
db:close()
?>
</pre></body></html>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment