LUA Mysql connection code


-- http://stackoverflow.com/questions/6318525/lua-mysql-need-a-way-to-escape-data
local put = cgilua.put;
function rows (connection, sql_statement)
  local cursor = assert (connection:execute (sql_statement))
  return function ()
    return cursor:fetch()
  end
end

cgilua.htmlheader()
put("<html><head><title>MYSQL in LUA</title></head>")
put("<body>");
put("<div class='main'>");


require "luasql.mysql"
env = assert(luasql.mysql())
con = env:connect("lua_db_mysql", "root", "", "localhost")

cgilua.put('Display MYSQL Data<br />----------------------------------------------<br />');
cgilua.put('<table border="1">');
cgilua.put('<tr>');
cgilua.put('<th>Id</th><th>Name</th><th>Address</th>');
cgilua.put('</tr>');
for id, name, address in rows (con, "select * from lua_table_mysql") do

cgilua.put('<tr>');
	cgilua.put('<td>'..string.format(id)..'</td>'); -- string concat with ..
	cgilua.put('<td>'..string.format(name)..'</td>');
	cgilua.put('<td>'..string.format(address)..'</td>');
  cgilua.put('</tr>');
end
cgilua.put('</table>');

put("</div>");
put("</body></html>");

Create database ‘lua_db_mysql’.

Mysql Table is below.

SET NAMES utf8;
SET foreign_key_checks = 0;
SET time_zone = 'SYSTEM';
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';

DROP TABLE IF EXISTS `lua_table_mysql`;
CREATE TABLE `lua_table_mysql` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `address` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

INSERT INTO `lua_table_mysql` (`id`, `name`, `address`) VALUES
('',	'php',	'php street'),
('',	'lua',	'lua street'),
('',	'mysql',	'mysql street');

Share on Facebook




About Pragnesh Karia

Pragnesh Karia, Open Source Enthusiast, Software Professional, Software Developer, Technical Lead ,Magento, Joomla ,Joomla LMS , Moodel LMS ,PHP ,Mysql, Ajax, Javascript, Jquery, Linux, Fan of Open Sources , Annet Technologies , SEO Analyst , Mootools