Skip to content

Instantly share code, notes, and snippets.

@billywhizz
Created May 10, 2011 20:24
Show Gist options
  • Save billywhizz/965308 to your computer and use it in GitHub Desktop.
Save billywhizz/965308 to your computer and use it in GitHub Desktop.
node-mysql v php/mysqli
var mysql = require("mysql/client");
var http = require("http");
var client = mysql({
"host": "127.0.0.1",
"port": 3306,
"user": "root",
"password": "password"
});
client.on("error", function(err) {
console.log(err);
});
client.connect(function(err) {
if(err) throw(err);
client.useDatabase("test", function(err) {
});
});
var header = "<html><head><title>MySQL Table Viewer</title></head><body>";
var footer = "</body>";
var httpd = http.createServer(function(req, res) {
var buff = [];
var sql = "select * from test";
client.query(sql, [], function(err, results) {
if(err) throw(err);
buff.push(header);
buff.push("<h1>Table: cameras</h1>");
buff.push("<table border='1'><tr>");
var first = results[0];
for(name in first) {
buff.push("<td>" + name + "</td>");
}
buff.push("</tr>");
results.forEach(function(camera) {
buff.push("<tr>");
for(name in first) {
buff.push("<td>" + camera[name] + "</td>");
}
buff.push("</tr>");
});
buff.push("</table>");
buff.push(footer);
res.end(buff.join(""));
});
});
httpd.listen(83, "0.0.0.0");
<html>
<head>
<title>MySQL Table Viewer</title>
</head>
<body>
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'password';
$database = 'test';
$table = 'test';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment