简体   繁体   English

如何将MYSQL表的选定行显示到HTML页面的示例表中?

[英]How can I display the selected row of an MYSQL table into a sample table of an HTML page?

I'm trying to add selected data row from mysql db into a html table. 我正在尝试将mysql数据库中的选定数据行添加到html表中。
In fact i can select data and show it in console but I don't know how to add it in html page. 实际上,我可以选择数据并将其显示在控制台中,但是我不知道如何在html页面中添加数据。

here is my js code 这是我的js代码

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  //Select all customers and return the result object:
  con.query("SELECT * FROM customers", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

Create an HTTP server, you can use the node http package but there are multiple frameworks which will make your life easier to do such tasks efficiently and safely. 创建一个HTTP服务器,您可以使用node http包,但是有多个框架可以使您的工作更轻松,更高效,更安全。

I will explain how to it basically with express.js and the jade template engine. 我将主要使用express.js和jade模板引擎说明如何进行此操作。 You will need jade and express dependencies. 您将需要玉器并表达依赖性。 So in your project folder: npm i express jade --save 因此,在您的项目文件夹中: npm i express jade --save

You will need to create a views folder which will contain your jade templates. 您将需要创建一个包含玉模板的views文件夹。 Here is the project structure. 这是项目结构。

/node_modules
/views
    index.jade
index.js

First file 第一个档案

// index.js file
// Create an express app
const app = require('express')();

// Create your mysql conn
const mysql = require('mysql');
const con = mysql.createConnection({
   host: "localhost",
   user: "root",
   password: "",
   database: "mydb"
});

// set view engine
app.set('view engine', 'jade');

// create a route handler, GET/
app.get('/', function (req, res) {
    // fetch your mysql data
    con.query("SELECT * FROM customers", function (err, result, fields) {
        if (err) throw err;
        // pass your data to your template file
        res.render('index', {data: result});
    });
});

// open your mysql connection and start express app
con.connect(function(err) {
   if (err) throw err;
   //Select all customers and return the result object:
   app.listen(8090);
});

Your template file 您的模板文件

// /views/index.jade
each d in data
  p
    = d.someproperty

This is very basic application but it will give you an understanding of how to create a basic http server, get data from your server and display it. 这是一个非常基础的应用程序,但是它将使您了解如何创建基本的http服务器,从服务器获取数据并显示它。

Note that there is also another way, which is to create a REST api and return your data as JSON and display it in a static website making an AJAX call. 请注意,还有另一种方法,即创建一个REST api并将您的数据作为JSON返回并在进行AJAX调用的静态网站中显示。

You can send query results to the client with socket.io. 您可以使用socket.io将查询结果发送到客户端。 Then you can add results to your html in the client. 然后,您可以将结果添加到客户端的html中。 Suppose your 'customers' table has the following structure: 假设您的“客户”表具有以下结构:

name varchar(20)
password varchar(20)

and you have empty element in your html. 并且您的html中有空元素。 You can emit 'customers' event in the server: 您可以在服务器中发出“客户”事件:

con.query("SELECT * FROM customers", function (err, results, fields) {
    if (err) throw err;
    console.log(result);
    // we only send results as we know the fields
    socket.emit('customers', results); 
  });

And in the client's code (pug or jade): 并在客户的代码(pug或玉)中:

script.
   let socket = io();
   socket.on('customers', data => {
       for (let i = 0, max = data.length; i < max; i++) {
           document.getElementById('customers').innerHTML += data[i].user + ' ' + data[i].password + '<br/>;
       }
   });

If you don't know the table fields (it is hardly possible, isn't it?) you can use both results and fields returned by the query as in the following example: 如果您不知道表字段(几乎不可能,不是吗?),则可以同时使用results和查询返回的fields ,如以下示例所示:

server.js: server.js:

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const mysql = require('mysql');

let con = mysql.createPool({
    connectionLimit: 10,
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'mydb'
});


io.on('connection', function (socket) {
    console.log('client connected');

    socket.on('show', () => {
        con.query('SELECT * FROM customers', (err, results, fields) => {
            if (err) {
                throw err;
            }
            //we send both: results and fields here as we don't know the fields
            socket.emit('customers', {results: results, fields: fields});  
        });
    });
});

http.listen(3000, function(){
    console.log('server listening on *:3000');
});

app.set('views', __dirname);
app.set('view engine', 'pug');
app.get('/', (req,res) => {
    res.render('index');
});

index.pug: index.pug:

doctype html
html
head
    meta(charset="UTF-8")
    script(src="/socket.io/socket.io.js")
body
    style.
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
        }
        th, td {
            padding: 5px;
        }
        #mysql {
            margin-top: 10px;
        }
    div
        h3 Query results
        button(id='show') Show
    #mysql
    script.
        let socket = io();
        socket.on('customers', data => {
            let mysql = document.getElementById('mysql');
            let table = document.createElement('TABLE');
            mysql.appendChild(table);
            let tableHead = document.createElement('THEAD');
            table.appendChild(tableHead);
            let tr = document.createElement('TR');
            tableHead.appendChild(tr);
            for (let i = 0, max = data.fields.length; i < max; i++) {
                let th = document.createElement('TH');
                th.width = '75';
                th.appendChild(document.createTextNode(data.fields[i].name));
                tr.appendChild(th);
            }
            let tableBody = document.createElement('TBODY');
            table.appendChild(tableBody);

            for (let i = 0, max = data.results.length; i < max; i++) {
                let tr = document.createElement('TR');
                for (let k = 0, max = data.fields.length; k < max; k++) {
                    let td = document.createElement('TD');
                    td.appendChild(document.createTextNode(data.results[i][data.fields[k].name]));
                    tr.appendChild(td);
                }
                tableBody.appendChild(tr);
            }
        });
        document.getElementById('show').addEventListener('click', () => {
            socket.emit('show');
        });

Here we retrieve information about the fields of the table from data.fields and use it in building the table. 在这里,我们从data.fields检索有关表字段的信息,并将其用于构建表。 So we only have to have access to the database and know the name of the table. 因此,我们只需要访问数据库并知道表的名称即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM