5

I know this question has been asked numerous times, but after search ferociously, I can not seem to find the answer I am looking for. I have a script in *.js format that creates a json data array then stores it in a json file.

The array setup is:

var sessionState = {
    currentWalletNdx: 0,
    genesisBlockId: 0,
    genesisBaseTarget: 0,
    genesisBlockTimestamp: 0,
    current: {
        blockHeight: 0,
        baseTarget: 0,
        startTime: 0,
        totalShare: 0,
        submitters: 0,
        bestDeadline: 0,
        totalPayments: 0,
        netDiff: 0
    },
    prevBlocks: []
};

And to store the data in a json file the function is:

saveSession: function () {
    var jsonData = JSON.stringify(sessionState, null, 2);
    fs.writeFileSync('pool-session.json', jsonData);
},

My question is, how can I write it in this js file to store the saved json array in a mysql table using the json type so I view the data later using php & mysql?

2
  • I'm thinking you're using nodejs, am I right? Commented Sep 8, 2017 at 0:35
  • Yes I am. I know how to make a connection in node js to a mysql db but am unsure as to handle to data and insert it Commented Sep 8, 2017 at 0:56

1 Answer 1

0

Something like this should work:

var mysql = require('mysql');
var database = mysql.createConnection({
  host: 'host',
  user: 'user',
  password: 'password',
  database: 'database'
});
database.connect(function(connectionError){
  if(connectionError){
    throw connectionError;
  }
  var sql = "INSERT INTO table(column) VALUES ('" + jsonData + "')";
  database.query(sql, function(queryError, queryResult){
    if(queryError){
      throw queryError;
    }
  });
});

Change table for the name of your table and column for the name of the column where you want to insert the JSON. And, of course, the database connection information

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

2 Comments

Isn't this vulnerable to SQL injection though?
Yes it is, but I assumed it was something fast to store the numbers and access them in another environment. I could be wrong though, so I upvoted your comment in case someone else comes looking for this

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.