Created
June 30, 2011 15:48
-
-
Save cfaulkingham/1056511 to your computer and use it in GitHub Desktop.
This example shows how to setup up a web server on port 8000 and fetch 10 results from a mysql database and outputing the results in html
This file contains 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
// Hacked together from http://utahjs.com/2010/09/22/nodejs-and-mysql-introduction/ | |
// Colin Faulkingham | |
// This example shows how to setup up a web server on port 8000 | |
// and fetch 10 results from a mysql database and outputting those results to HTML | |
// | |
// Version 2.0 | |
// I cleaned up the code to be more readable. | |
var http = require('http'); | |
var Client = require('mysql').Client; | |
var client = new Client(); | |
var server = http.createServer(function (req, res) { | |
dbh(req,res); | |
}); | |
server.listen(8000); | |
var dbh = function(req,res){ | |
client.host ='your.server.name'; | |
client.user = 'mysql_user'; | |
client.password = 'mysql_pass'; | |
client.connect(function(err, results) { | |
if (err) { | |
console.log("ERROR: " + err.message); | |
throw err; | |
} | |
dbquery(client,res,req); | |
}); | |
} | |
var dbquery=function(client,res,req) | |
{ | |
client.query( | |
'SELECT * FROM your_database_name.your_column ORDER BY your_column ASC LIMIT 0,10', | |
function (err, results, fields) { | |
if (err) { | |
console.log("ERROR: " + err.message); | |
throw err; | |
} | |
res.writeHead(200,{'Content-type': 'text/html'}); | |
res.write('<html>\n<head><title>node.js rocks</title></head>\n<body>'); | |
console.log("Got "+results.length+" Rows:"); | |
for(var i in results){ | |
res.write('<p>'+results[i].your_column_Name+'</p>'); | |
} | |
res.write('</body></html>\n'); | |
client.end(); | |
res.end(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment