Schmaniel
Schmaniel

Reputation: 105

Why can't I UPDATE MySQL with an string?

I have three vars that I want to update to an mysql database.

var rank = "Bronze II";
var wins = 304;
var level = 51;

Why can't I update the database with my Bronze II string? If I change it to an number it's working.

pool.getConnection(function(err, connection) {
    if (err) throw err;
    connection.query("UPDATE Users SET Rank = " + rank + ", Wins = " + wins + ", Level = " + level + " WHERE SteamID64 = " + `${row.SteamID64}` +"");
    connection.release();
    if (err) throw err;
});

Upvotes: 0

Views: 219

Answers (1)

Mat Sz
Mat Sz

Reputation: 2552

You should use a prepared query instead.

connection.query('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', ['a', 'b', 'c', userId], function (error, results, fields) {
    if (error) throw error;
    // ...
});

With your data:

connection.query("UPDATE Users SET Rank = ?, Wins = ?, Level = ? WHERE SteamID64 = ?", [ rank, wins, level, row.steamID64 ]);

This will improve the security of your application and help you avoid similar problems in the future. (Imagine if your data had a " character inside?)

You should do this to all queries that rely on external input, instead of concatenating strings.

Upvotes: 2

Related Questions