1

I made a project where i include database which i wrote on mysql and it make a json file from database and also output all users in browser but I have some problem. I want to output one user how can i do this(this is example how it must output http://localhost:8080/user/1). I used express and mysql. Please help me. Thanks.

This is my code:

'use strict';
const mysql = require('mysql');
const express = require('express');
const http = require('http');
const router = express()

// http://nodejs.org/docs/v0.6.5/api/fs.html#fs.writeFile
const fs = require('fs');

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'lado',
    password: '1234'
});

connection.connect();

connection.query('SELECT * FROM bankdb.account;', function(err, results, fields) {
    if(err) throw err;

    fs.writeFile('account.json', JSON.stringify(results), function (err) {
        if (err) throw err;
        console.log('Saved!');
    });
    connection.end();
});


const pool = mysql.createPool({
    host: 'localhost',
    user: 'lado',
    password: '1234',
    database: 'bankdb',
    charset: 'utf8'
});
var reo ='<html><head><title>Output From MYSQL</title></head><body><h1>Output From MYSQL</h1>{${table}}</body></html>';
function setResHtml(sql, cb){
    pool.getConnection((err, con)=>{
        if(err) throw err;

        con.query(sql, (err, res, cols)=>{
            if(err) throw err;

            var table =''; //to store html table

            //create html table with data from res.
            for(var i=0; i<res.length; i++){
                table +='<tr><td>' + (i+1) +'</td><td>'+ res[i].name +'</td><td>'+ res[i].address +'</td></tr>';
            }
            table ='<table border="1"><tr><th>ID</th><th>Name</th><th>Amount</th></tr>'+ table +'</table>';

            con.release(); //Done with mysql connection

            return cb(table);
        });
    });
}

const sqll ='SELECT * FROM bankdb.account';

const server = http.createServer((req, res)=>{
    setResHtml(sqll, resql=>{
        reo = reo.replace('{${table}}', resql);
        res.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
        res.write(reo, 'utf-8');
        res.end();
    });
});

server.listen(8080, ()=>{
    console.log('Server running at //localhost:8080/');
    router.get('/users/:id', function(req, res, next) {
        var user = users.getUserById(req.params.id);
        res.json(user);
    });
    exports.getUserById = function(id) {
        for (var i = 0; i < users.length; i++) {
            if (users[i].id == id) return users[i];
        }
    };
});

1 Answer 1

1

Just get the specific user based on their id:

router.get( '/user/:id', function( req, res ) { // When visiting '/user/:id'

   var id = req.params.id; // For example if you visit localhost/user/24 the id will be 24

   connection.query('SELECT * FROM bankdb.account WHERE id=' + mysql.escape( id ), function(err, results, fields) {
       if(err) throw err;

       fs.writeFile('account.json', JSON.stringify(results), function (err) {
         if (err) throw err;
         console.log('Saved!');
       });
       connection.end();
   });

} );

If you grab every user from the database, your program will use up much more memory.

Just grab the one you need and work with him.

Sign up to request clarification or add additional context in comments.

4 Comments

I shoud add it in server.listen(8080, ()=>{...} ? Cause when i add it here i show all users(I typed this http://localhost:8080/user/1) Sorry I'm just beginner
No worries. If I were you, I would place this outside the server.listen(). I usually put all router.get() and router.post() etc. methods before server.listen(). Also, I do not know what your database looks like. Just make sure every user has an id field. That way you can search through the database based on their user id.
It should work properly. If you visit the website you will not get any response but a new file should be created.
Ooooh okay. Thanks)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.