1

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?

yrbet
  • 151
  • 6

1 Answers1

1

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/

Charlie
  • 18,636
  • 7
  • 49
  • 75
  • yes, it works! and I has one more question, how I can insert data if this not exist? because when I restart app and it insert data, it make duplicates all information, with new ID in column – yrbet Apr 10 '21 at 07:23
  • This question discusses your new scenario: https://stackoverflow.com/questions/1361340/how-to-insert-if-not-exists-in-mysql – Charlie Apr 10 '21 at 07:57