Search code examples
javascriptmysqlnode.jsnode-mysql

Can't seem to query specific things using node-mysql with JavaScript


p_info_query('SELECT * FROM ' + <table> + ' WHERE name = ' + user_name, password, client_connect.id, p_info, function(results) {

This seems to produce a Unknown Column 'user_name'. I searched online for some examples of people doing this, but I couldn't find any. I want to query for specific things, maybe even comparing 2 values, user and password.

Any help?

// edited for p_info_query function

function p_info_query(sql, password, client_socket_id, player_info_object, callback) {
  var result =  mysql_client.query(sql, function (error, results, fields) {
    if (error) {
        console.log('ERROR IN MYSQL LOGIN CALLBACK : '+ error);
        return false;
    }
    if (results.length  > 0) {

    // do stuff


    callback(true);
    } else {

    callback(false);
    }
    }
}); 

Solution

  • Your problem is that you're not quoting the user_name so you end up with SQL like this:

    select * from table where name = whatever
    

    where whatever is the value of user_name, an unquoted value like that is parsed as an identifier (essentially a column name in that context), hence your "unknown column" error.

    Presumably p_info_query is something of your own as it isn't part of node-mysql. You should modify it to use placeholders so that it can do things like this internally:

    client.query(
        'select * from ' + table_name + ' where name = ?',
        [ user_name ],
        function(err, results, fields) { /* ... */ }
    );
    

    Note the ? in the SQL and the [user_name] array.


    Now that we know what p_info_query looks like, we can fix that too; you should update it look more like this:

    function p_info_query(sql, params, password, client_socket_id, player_info_object, callback) {
      var result =  mysql_client.query(sql, params, function (error, results, fields) {
        // ...
    

    Then you can say this:

    p_info_query(
      'SELECT * FROM ' + table_name + ' WHERE name = ?',
      [user_name],
      password,
      client_connect.id,
      p_info,
      function(results) { /* ... */ }
    );
    

    to use a placeholder.