yrbet
yrbet

Reputation: 191

NodeJS insert in mysql from array

I has simple function in nodejs, which add result to MYSQL. But result is coming in array, and i can't correctly add this data to the table.

My functions:

function getPreviousGames() {
    const previousGames = [];
    let gameHash = generateHash(crashHash);

    for (let i = 0; i < 1; i++) {
        const gameResult = crashPointFromHash(gameHash);
        previousGames.push({ gameHash, gameResult });
        gameHash = generateHash(gameHash);

    }
    return previousGames;
}

function verifyCrash() {
    const gameResult = crashPointFromHash(crashHash);
    const previousHundredGames = getPreviousGames();

    for (let i = 0; i < 1; i++) {

        var sql = "INSERT INTO `admin_dev`.`crash_numbers` (`id`, `hash`, `multiplier`, `status`, `created_at`, `updated_at`) VALUES (NULL, '" + previousHundredGames(gameHash) + "', '" + gameResult + "', '0', now(), now());";

        connection.query(sql, function (err, result) {
            if (err) throw err;
            console.log("Success!");

        });
    }

    return { gameResult, previousHundredGames };
}

And i received result:

{
  previousHundredGames: [
    {
      gameHash: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
      gameResult: 2.52
    }
  ]
}

And i can't correcly add this received data to mysql table.

I need add from previousHundredGames value gameHash to hash column, and gameResult value to multiplier column.

How i can correctly made it?

Upvotes: 1

Views: 120

Answers (1)

Charlie
Charlie

Reputation: 23768

If you are using a query, it is as simple as building an INSERT query.

//Start the query
let query= 'INSER INTO (hash, gameResult) VALUES ';

//Add multiple rows from the array
for (let aGame of previousGames)    
    query+= `( "${aGame.gameHash}", ${aGame.gameResult}),  `

//Remove the last comma
query= queryBuilder.substring(0, queryBuilder.length - 1)

Here is documentation on inserting multiple rows in a single query.

https://www.mysqltutorial.org/mysql-insert-multiple-rows/

Upvotes: 1

Related Questions